通过JSON API插件显示热门帖子

时间:2016-08-17 12:00:25

标签: wordpress wordpress-json-api

我正在使用JSON API插件以json格式检索其数据的工作正常。

现在我想使用相同的插件检索热门(观看次数最多)的帖子。我怎样才能做到这一点。

1 个答案:

答案 0 :(得分:0)

WordPress不存储每个帖子的视图数量,因此只有JSON API才能实现这一点。您需要在每个页面加载时运行存储在post_meta中的计数,例如:

function post_view_count() {
    if ( is_single() ) {
        $count = get_post_meta( get_the_ID(), 'post_view_count', true ) ?: 0;
        update_post_meta( get_the_ID(), 'post_view_count', $count++ );
    }
}
add_action( 'wp_head', 'post_view_count' );

然后,您可以查询API的一个帖子,按键“post_view_count”按降序排序。您可能需要添加类似的内容以允许使用API​​查询post_meta:

function json_allow_meta_query( $valid_vars ) {
    $valid_vars = array_merge( $valid_vars, array( 'meta_key', 'meta_value', 'meta_compare' ) );
    return $valid_vars;
}
add_filter( 'rest_query_vars', 'json_allow_meta_query' );

但是,请注意,您要为每次后期加载添加两个数据库匹配,这会影响性能。

相关问题