【收藏整理】WordPress 文章浏览数[新方法]

无论是WP-postviews还是传统的非插件实现文章浏览数,都是把数据储存在postmeta中,文章少无所谓了,文章多的话,你懂的,所以我就仿照评论数把浏览数储存在posts这个表中。

下面的代码加到functions.php

function the_view( $zero = false, $one = false, $more = false ){
    echo get_the_view( $zero, $one, $more );
}

function get_the_view( $zero = false, $one = false, $more = false ){
    $views = get_the_view_num();
    if ( $views > 1 ) {
        $output = str_replace( '%', restyle_text( $views ), ( false === $more ) ? '% reads' : $more );
    } elseif ( $views == 0 ) {
        $output = ( false === $zero ) ? 'No reads' : $zero;
    } else {
        $output = ( false === $one ) ? '1 read' : $one;
    }
    return $output;
}

function get_the_view_num( $post = 0 ){
    $post = get_post( $post );
    $views = isset( $post->post_views ) ? $post->post_views : '';
    if( is_singular() ) $views = $views + 1;
    return $views;
}

function restyle_text($number) {
    if($number >= 1000) {
       return round($number/1000,2) . "k";   // NB: you will want to round this
    }
    else {
        return $number;
    }
}

function fa_set_post_view() {
    global $post;
    $post_id = intval($post->ID);
    $views = intval($post->post_views);
    if (is_singular()) {
        fa_update_post_meta($post_id,'post_views',($views + 1));
    }
}
add_action('get_header', 'fa_set_post_view');

function fa_update_post_meta($id,$meta_type,$value){
    global $wpdb;
    $wpdb->update(
        $wpdb->posts,
        array(
            $meta_type => $value
        ),
        array( 'ID' => $id ),
        array(
            '%d'
        ),
        array( '%d' )
    );
}

function fa_get_total_views(){
    global $wpdb;
    $total_views = $wpdb->get_var("SELECT SUM(post_views) FROM $wpdb->posts WHERE post_status = 'publish'");
    return restyle_text( $total_views );
}

add_action( 'after_switch_theme', 'tgthemes_init' );
function tgthemes_init(){
    global $wpdb;		
		$tableposts	= $wpdb->posts;
		$wpdb->query("ALTER TABLE $wpdb->posts 
		ADD post_views BIGINT(20) NOT NULL;");

}

添加后切换下主题就可以了。

调用方法

<?php the_view(); ?>

三个参数和评论数的使用方法是一样的,可以自己定义显示单位,如果不打印出来则使用get_the_view()

调用总浏览数

<?php echo fa_get_total_views(); ?>

蜘蛛访问不增加浏览量

下面这个函数添加到functions.php

function is_spider(){
    $is_spider = false;
    $bots = array('Google Bot' => 'googlebot', 'Google Bot' => 'google', 'MSN' => 'msnbot', 'Alex' => 'ia_archiver', 'Lycos' => 'lycos', 'Ask Jeeves' => 'jeeves', 'Altavista' => 'scooter', 'AllTheWeb' => 'fast-webcrawler', 'Inktomi' => 'slurp@inktomi', 'Turnitin.com' => 'turnitinbot', 'Technorati' => 'technorati', 'Yahoo' => 'yahoo', 'Findexa' => 'findexa', 'NextLinks' => 'findlinks', 'Gais' => 'gaisbo', 'WiseNut' => 'zyborg', 'WhoisSource' => 'surveybot', 'Bloglines' => 'bloglines', 'BlogSearch' => 'blogsearch', 'PubSub' => 'pubsub', 'Syndic8' => 'syndic8', 'RadioUserland' => 'userland', 'Gigabot' => 'gigabot', 'Become.com' => 'become.com', 'Baidu' => 'baiduspider', 'so.com' => '360spider', 'Sogou' => 'spider', 'soso.com' => 'sosospider', 'Yandex' => 'yandex');
    $useragent = $_SERVER['HTTP_USER_AGENT'];
    foreach ( $bots as $name => $lookfor ) {
        if ( stristr( $useragent, $lookfor ) !== false ) {
            $is_spider = true;
            break;
        }
    }
    return $is_spider;
}

然后把fa_set_post_view()函数修改为

function fa_set_post_view() {
    global $post;
    $post_id = intval($post->ID);
    $views = intval($post->post_views);
    if (is_singular() && !is_spider()) {
        fa_update_post_meta($post_id,'post_views',($views + 1));
    }
}

数据转换方法

你可能使用了wp-postvies或者非插件的方法实现了这个功能,在你主题的页面插入下面的代码,然后访问下这个页面,再删除就行了。执行速度和你文章数和主机性能有关系。

<?php
$the_query = new WP_Query( 'posts_per_page=-1&ignore_sticky_posts=1' );
while ( $the_query->have_posts() ) : $the_query->the_post();
    $id = get_the_ID();
    $views = get_post_meta($id,"views",true);
    fa_update_post_meta($id,"post_views",$views );
endwhile;
wp_reset_postdata();
echo "<div class='updated'><p>数据迁移成功.</p></div>";
?>

鉴于一般博客文章都不超过1000,实际执行起来还是没什么问题的。

获取浏览数最多的文章

下面的代码加到functions.php

function get_most_views_posts($num = 5,$days = 7){
    global $wpdb;
    $today = date("Y-m-d H:i:s");
    $daysago = date( "Y-m-d H:i:s", strtotime($today) - ($days * 24 * 60 * 60) );
    $most_viewed = $wpdb->get_results("SELECT ID, post_title , post_views FROM $wpdb->posts WHERE post_type='post' post_date BETWEEN '$daysago' AND '$today' ORDER BY post_views DESC LIMIT $num");
    $temp = '<ul class="most_viewed">';
    if(empty($most_viewed)) {
        $temp .= '<li>Sorry,cannot find any post.</li>';
    }else{
        foreach ($most_viewed as $post) {
            $temp .= '<li><a href="' .get_permalink($post->ID).'">' . current_time('mysql') .$post->post_title. ' / ' . $post->post_views .' reads</a></li>';
        }
    }
    $temp .='</ul>';
    echo $temp;
}

使用<?php get_most_views_posts(5,30); ?>调用,第一个参数是文章数,第二个是多少天以内的文章。

本文转自:大发贱志

本文共 9 个回复

  1. 祥磊部落 says:
    在你的网站听到我非常喜欢的歌曲了 陈奕迅的不要说话 现在还是铃声呢
  2. Thiece says:
    姐姐最近在做些什么呢?
  3. Specs says:
    看有人说这个用WP导出功能的时候,里面会没有这个字段~
  4. 破小懿 says:
    喵~主题自带了,以后再折腾自己的主题吧,

发表留言,喵!