今天给大家分享,wordpress网站如何利用浏览量给文章排序,适用于调用分类的热门文章。

首先要在主题函数functions.php中加入下面代码:

//网站浏览量统计代码 
function themetuts_record_visitors(){ if (is_singular()) {
 global $post; $post_ID = $post->ID; if($post_ID) { $post_views = (int)get_post_meta($post_ID, 'views', true); if(!update_post_meta($post_ID, 'views', ($post_views+1))) { add_post_meta($post_ID, 'views', 1, true); } } } } add_action('wp_head', 'themetuts_record_visitors'); function themetuts_the_view($before = '', $after = '', $echo = 1) { global $post; $post_ID = $post->ID; $views = (int)get_post_meta($post_ID, 'views', true); if ($echo) echo $before, number_format($views), $after;
 else return $views; }

上面是显示浏览量的代码,在循环中可以用下面标签调用

<?php themetuts_the_view(); ?>

按浏览量排序的代码如下:

<?php$args=array('meta_key' => 'views','orderby' => 'meta_value','order' => 'date');query_posts($args);while ( have_posts() ) : the_post();?>								
    <li>
        <a href="<?php%20the_permalink()%20?>" title="<?php the_title(); ?>">
            <?php if(has_post_thumbnail()) {the_post_thumbnail('post');} else { ?><img src="<?php%20echo%20get_template_directory_uri();?>/images/thumbnail/<?php%20echo%20rand(1,6);?>.png" alt="<?php the_title(); ?>" /><? } ?>
            <span class="itemtit"><?php the_title(); ?></span>
            <span class="itempoint clr">
                <span class="price">¥<?php the_field('price'); ?></span>
                <span class="hots"><span class="fa fa-sun-o"></span><?php themetuts_the_view(); ?></span>
            </span>
        </a>
    </li><?php endwhile;wp_reset_query();?>