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

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

收藏
评论
打赏
WordPress 插件开发
上一篇
WordPress 常用接口
下一篇

发表评论

像素鱼丸
58227 阅读
98 发布
3 收藏
动态
MirageV 主题 v2.6.4 发布
LandV 企业主题 v2.6.0 发布
FishV 主题 v1.14 发布
BotV 插件 v1.7.0 发布
MirageV 主题 v2.5 正式发布
FishV 主题 v1.21.0 发布
MirageV 主题 v2.6.0 发布
MirageV-App 小程序 v1.2.2 发布
生成中...
真诚赞赏,手留余香
登录
注册
重置密码