WordPress 添加文章浏览次数

1,数据库相关表

WordPress 文章表中是没有文章点击次数这个字段的,所以把文章点击次数,保存在表 wp_postmeta 中。

2, 通用函数

/**
 * 设置文章浏览次数
 */
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, '1');
    } else {
        $count++;
        update_post_meta($postID, $count_key, $count);
    }
}


/**
 * 获取文章浏览次数
 */
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;
}

3,在文章也可以使用

setPostViews(get_the_ID()); // 更新文章浏览次数
getPostViews(get_the_ID()); // 获取文章浏览次数

以上是文章浏览次数,其他字段,比如点赞之类的,也可以使用此种方法。

收藏 0
评论
WordPress 插件开发
WordPress 插件开发
2023-05-04 15:08:52
RESTful API 开发
WordPress 常用接口
2023-05-04 15:13:04
生成中...
登录
注册
重置密码