获取特定帖子的已排队/已注册脚本列表?

时间:2018-11-23 作者:Alvaro

我正在探索如何构建一个主题,其中大多数页面都是使用RESTAPI加载的。我可以加载索引页面,并从那里发出GET请求以获取posts json数据,然后在当前页面中构建其内容。基本上是aSPA, 至少在某种程度上。

当尝试加载单个帖子及其脚本/样式时,就会出现问题。例如,Gutenberg允许使用enqueue_block_assets

我正在试图找到一种方法来获取特定帖子的注册样式和脚本url。我的想法是注册rest route 或afield 返回每个脚本/样式的url。然后,在装载完单个post json数据后,我可以将每个脚本/样式附加到DOM。

global $wp_scripts; 返回当前页面加载中已注册的脚本和已排队的脚本。因此,我无法找到从单页加载流之外指定post id来获取该信息的方法。

如何获取任何特定帖子id的排队/注册脚本和样式url列表?

有没有更好的方法?

1 个回复
SO网友:Johansson

我对古腾堡并不熟悉,但正如你所提到的例子,我想你不是指“仅”古腾堡。

这个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

}

结束

相关推荐

Php致命错误:无法将WP_REST_RESPONSE类型的对象用作wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php中

我向WordPress添加了一个自定义端点,如下所示: add_action( \'rest_api_init\', function () { register_rest_route( \'menc/v1\', \'/crosscat/(?P[\\w-]+)/(?P[\\w-]+)\', array( \'methods\' => \'GET\', \'callback\' => \'dept_cat_api\',&#x