我对古腾堡并不熟悉,但正如你所提到的例子,我想你不是指“仅”古腾堡。
这个wp_enqeue_script() 或wp_enqueue_style() 函数不接受有关帖子或页面的参数。脚本是全局注册和呈现的。如果脚本仅在某些帖子上输出,那么它必须是本机PHP条件,这很难确定。
一个想法是只包含一个index.php 在主题中归档,并仅添加wp_head() 和wp_footer() 在里面。然后在每个rest请求中,使用wp_remote_get() 并运行preg_match_all() 从该页面提取所有脚本,并将其添加到rest字段。这有点乱,但很可靠。
不要忘记在瞬态或对象缓存中缓存结果,以提高性能。
下面是一个基本示例,介绍如何执行此操作:
// Let\'s register a new field for returning the script srcs
add_action( \'rest_api_init\', \'wpse320065_register_rest_field\' );
function wpse320065_register_rest_field() {
register_rest_field(
\'post\',
\'your-field-name\',
[
\'get_callback\' => \'wpse320065_fetch_post_cont\',
\'schema\' => null,
]
);
}
// Callback function to actually retrieve the data
function wpse320065_fetch_post_cont( $object ) {
// Get the id of the post object array
$post_id = $object[\'id\'];
// Let\'s get the content of post number 123
$response = wp_remote_get( "http://example.com/?p={$post_id}" );
if ( is_array( $response ) ) {
$content = $response[\'body\'];
// Extract the src attributes. You can also use preg_match_all
$document = new DOMDocument();
$document->loadHTML( $content );
// An empty array to store all the \'srcs\'
$scripts_array = [];
// Store every script\'s source inside the array
foreach( $document->getElementsByTagName(\'script\') as $script ) {
if( $script->hasAttribute(\'src\') ) {
$scripts_array[] = $script->getAttribute(\'src\');
}
}
}
return $scripts_array
}