如何在内容管理系统(Nuxt.js + WordPress)中通过API获取浏览排名

我在Nuxt.js上为博客创建了一个内容管理系统(在前端)。内容管理系统使用WordPress作为其后端,并使用'WP REST API‘在Nuxt.js中显示文章。(因为我想减少使用WordPress创建管理屏幕所花费的时间。)

这里有一些需要实现的特性。它是文章的浏览排名。

使用以下插件和代码按查看次数的顺序从站点检索文章。

插件: WordPress Popular Posts https://wordpress.org/plugins/wordpress-popular-posts/

我将以下代码添加到WordPress上的functions.php中

class WPP_REST_Controller {
    public function __construct() {
        $this->namespace     = '/wpp';
        $this->resource_name = '/posts';
    }

    public function register_routes() {
        register_rest_route( $this->namespace , $this->resource_name, array(
            'methods'  => 'GET',
            'callback' => array($this, 'get_wpp'),
        ) );
    }


    public function get_wpp( $request ) {
        if (function_exists('wpp_get_mostpopular')) {
            $args = array(
                'limit' => 10,
                'stats_views' => 0,
                'wpp_start' => '{',
                'wpp_end' => '}',
                'post_html' => '{pid},',
            );
            ob_start();
            wpp_get_mostpopular( $args );
            $str = ob_get_contents();
            ob_end_clean();
            $str = str_replace("\n", '', $str);
            preg_match('/\{(([0-9]*,)*)\}/s', $str, $match);
            if (count($match)) {
                $ids = rtrim($match[1], ',');
                $url = get_bloginfo('url') . '/wp-json/wp/v2/posts?include=' . $ids;
                header("Location: " . $url);
                exit;
            }
        }
    }
}


function prefix_register_my_rest_routes() {
    $controller = new WPP_REST_Controller();
    $controller->register_routes();
}


add_action( 'rest_api_init', 'prefix_register_my_rest_routes' );

Nuxt.js(ranking.vue):

<template>
  {{top_articles}}
</template>
<script>
export default {
  data() {
    return {
      top_articles
    };
  },
  async asyncData({ $axios, params }) {
    const top_articles = await $axios.$get('http://example.com/wp-json/wpp/posts');
}
</script>

但是有一个问题。通过Nuxt.js查看的文章数量不会反映在接口响应中。

文章展示页面如下:

文章(Nuxt.js/_id.vue)

<template>
  {{ article }}
</template>
<script>
export default {
  data() {
    return {
      article: this.article,
    }
  },
  async asyncData({ $axios, params }) {
    const article = await $axios.$get('http://example.com/wp-json/wp/v2/posts/' + params.id);
    return { article };
  }
}
<script>

请告诉我,我应该做些什么来实现上述目标。(我可以使用其他插件。)

转载请注明出处:http://www.intrusion-fire.net/article/20230329/1119679.html