如何给 WordPress 添加文章阅览计数功能

post-count

对文章阅览量做计数是一个网站比较通用的功能,wordpress 目前还没有提供这样的功能,但是可以利用 wordpress 内置的元数据管理功能接口实现文章阅览量计数的功能。wordpress 元数据管理功能接口是 wordpress 提供一种动态扩展数据的接口,可以通过程序的方式实现扩展现有数据库的需求,比如增加新的与文章相关的元数据。

使用 wordpress 元数据实现文章计数功能的主要思路就是以文章的唯一识别 id 做为元数据关键值来存放文章计数的字段和数值,当用户点击文章时通过 post id 获取该文章的元数据,如果该文章的元数据不存在,则新增元数据并对阅览量计数字段置零,如果存在则对计数做加一的处理并保存到该文章的元数据里,实现代码如下:

function set_post_views($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);
    }
}
function count_post_views ($post_id) {
    if ( !is_single() ) return;
    if ( empty ( $post_id) ) {
        global $post;
        $post_id = $post->ID;    
    }
//对相册、视频类型的文章不做计数
    $p_format = get_the_terms( $post_id, 'post_format' );
    if ( !empty( $p_format ) ) {
	$format = reset( $p_format );
	$format_str = str_replace( 'post-format-', '', $format->slug );
	if( $format_str == 'gallery' || $format_str == 'video' ) return;
    }
    set_post_views($post_id);
}
add_action( 'wp_head', 'count_post_views');

把这段代码添加到 functions.php 中。 另外,使用 Ajax 实现文章阅览计数的方法请参看这篇文章

发表评论

邮箱地址不会被公开。 必填项已用*标注