如何在CMS(Nuxt.js + WordPress)中按API获取浏览排名



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

这里有一些功能需要实现。 这是文章浏览排名。

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

插件: WordPress热门帖子 https://wordpress.org/plugins/wordpress-popular-posts/

我在WordPress上.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查看的文章数量不会反映在API响应中。

文章显示页面如下所示:

Nuxt.js(article/_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>

请告诉我我应该怎么做才能实现上述目标。 (我可以使用其他插件。

我解决了自己。 WordPress Popular Posts插件有一种通过API计算浏览

量的方法。参考网址: https://wordpress.org/support/topic/wpp-with-an-ajax-based-site/

我修改了"article/_ 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);
// WordPress Popular Posts Counts Up Visits
$axios.$post(
'http://example.com/wp-json/wordpress-popular-posts/v1/popular-posts?wpp_id=' +
params.id,
)
return { article };
}
}
<script>

最新更新