wordpress默认是没有阅读数的,本文通过使用wordpress内部的set_post_meta方法来实现。在主题文件的functions.php增加以下代码:

/**
 * 增加浏览数
 **/
function getPostViews($postID){
    $count_key = 'post_views_count';  
    $count = get_post_meta($postID, $count_key, true);  
    if($count==''){
        delete_post_meta($postID, $count_key);  
        add_post_meta($postID, $count_key, '0');  
        return "0";   
    }  
	return $count;
}  

function setPostViews($postID) {  
    $count_key = 'post_views_count';  
    $count = get_post_meta($postID, $count_key, true);  
    if($count==''){  
        $count = 0;  
        delete_post_meta($postID, $count_key);  
        add_post_meta($postID, $count_key, '0');  
    }else{  
        $count++;  
        update_post_meta($postID, $count_key, $count);  
    }  
}
/**
 * 在接口增加 post_view 字段
 **/ 
add_action( 'rest_api_init', function () {
    register_rest_field( 'post', 'post_view_count', array(
        'get_callback' => function($post) {
            return getPostViews($post['id']);
        },
    ) );
} );

在single.php文件放入以下代码,这样每次打开都会把阅读数加一。

<?php setPostViews(get_the_ID()); ?>

在需要现实阅读数的地方,加入以下代码

<?php echo getPostViews(get_the_ID()); ?>

最后一段函数是把阅读数加入wp rest api的返回。key=post_view_count。
官方说明https://developer.wordpress.org/rest-api/extending-the-rest-api/modifying-responses/

版权声明:如无特别声明,本文版权归 一年四季 所有,转载请注明本文链接。

(采用 CC BY-NC-SA 4.0 许可协议进行授权)

本文标题:《 wordpress增加阅读数(含接口改造) 》

本文链接:https://www.yucanlin.cn/develop/wordpress%E5%A2%9E%E5%8A%A0%E9%98%85%E8%AF%BB%E6%95%B0-%E5%90%AB%E6%8E%A5%E5%8F%A3%E6%94%B9%E9%80%A0.html

Contents