Home >  > 不用插件给wordpress添加热门文章功能

不用插件给wordpress添加热门文章功能

一、function php

function wpb_set_post_views($postID) {
    $count_key = 'wpb_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);
    }
}
//To keep the count accurate, lets get rid of prefetching
remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0);


function wpb_track_post_views ($post_id) {
    if ( !is_single() ) return;
    if ( empty ( $post_id) ) {
        global $post;
        $post_id = $post->ID;    
    }
    wpb_set_post_views($post_id);
}
add_action( 'wp_head', 'wpb_track_post_views');


/**
用于显示浏览次数最多的文章
*/
function wpb_get_post_views($postID){
    $count_key = 'wpb_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;
}

二、文章页面调用函数
在文章页面的主循环里面添加下面的代码(添加到endwhile前面即可):

<?php wpb_set_post_views(get_the_ID());	?>	

三、显示文章浏览次数

浏览:<?php echo wpb_get_post_views(get_the_ID()); ?> 次<

四、在需要显示“浏览次数最多的文章”里面添加以下代码:

                    <?php 
                    $popularpost = new WP_Query( array( 'posts_per_page' => 10, 'meta_key' => 'wpb_post_views_count', 'orderby' => 'meta_value_num', 'order' => 'DESC'  ) );
                    while ( $popularpost->have_posts() ) : $popularpost->the_post();
                    ?>


                    <li> 
                    <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>">
                    <?php      
                    the_title();
                    ?>
                    </li>


                    <?php  
                    endwhile;
                    ?>  

参考:

https://www.wpbeginner.com/wp-tutorials/how-to-track-popular-posts-by-views-in-wordpress-without-a-plugin/

暧昧帖

本文暂无标签