个性化阅读
专注于IT技术分析

如何通过wordpress API端点返回内容

点击下载

因此, 我一直在尝试扩展Wordpress API以获取Wordpress在<head>中输出的内容。

我已经在主题的functions.php中注册了端点, 如下所示:

add_action('rest_api_init', function () {
  register_rest_route( 'hs/v1', 'header', array(
                'methods'  => 'GET', 'callback' => 'get_head_content'
      ));
});

回调如下所示, 但只为每个键返回空数组:

function get_head_content() {

    $result = [];
    $result['scripts'] = [];
    $result['styles'] = [];

    // Print all loaded Scripts
    global $wp_scripts;
    foreach( $wp_scripts->queue as $script ) :
       $result['scripts'][] =  $wp_scripts->registered[$script]->src . ";";
    endforeach;

    // Print all loaded Styles (CSS)
    global $wp_styles;
    foreach( $wp_styles->queue as $style ) :
       $result['styles'][] =  $wp_styles->registered[$style]->src . ";";
    endforeach;

    return $result;
}

因此, 我的猜测是get_head_content不返回任何内容, 因为什么都没有入队, 因为我实际上没有通过点击API端点来触发队列。这实际上并没有将整个<head>输出为字符串, 这也不是我的主要目标。

有谁知道如何实现这一目标?

感谢帮助!


#1


你可以使用输出缓冲区和get_header:

function get_head_content() {
    ob_start();
    get_header();
    $header = ob_get_contents();
    ob_end_clean();

    return $header ;
}
赞(0)
未经允许不得转载:srcmini » 如何通过wordpress API端点返回内容

评论 抢沙发

评论前必须登录!