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


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


修改时间 2023-11-14

声明:本站所有文章和图片,如无特殊说明,均为原创发布。商业转载请联系作者获得授权,非商业转载请注明出处。
真诚赞赏,手留余香
赞赏
随机推荐
WordPress 实现自定义 Ajax 请求
Debian11 安装笔记2:编译安装PHP
SQL 注入的生命力
WordPress 语言文件
MySQL 表名预处理
Node.js 使用 Jest 做单元测试
WordPress 函数 add_option()、get_option() 和 update_option()
如何使用命令修改 MySQL 数据库名称