在WordPress中文章的浏览量是经常要用到的一个功能,为您的文章添加一个统计,可以很方便的知道到底有多少人在查看这篇文章,目前现在的主题大部分都集成了此功能,但是WordPress部分主题并没有提供WordPress浏览量功能,如果您的WordPress主题没有此功能或者正在学习WordPress开发,那么通过以下代码可以实现哦,放入function中:
WordPress浏览量
//网站浏览量统计代码
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(); ?>
WordPress浏览量文章排序
<?php
$args=array(
'meta_key' => 'views',
'orderby' => 'meta_value',
'order' => 'date'
);
query_posts($args);
while ( have_posts() ) : the_post();
?>
<li>
<a href="<?php the_permalink() ?>" title="<?php the_title(); ?>">
<?php if(has_post_thumbnail()) {the_post_thumbnail('post');} else { ?><img decoding="async" src="<?php echo get_template_directory_uri();?>/images/thumbnail/<?php echo rand(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();?>
好了这样就算为您的WordPress主题上增加上了浏览量功能,如果您需要浏览量文章排序可以采用最后的方法,本WordPress浏览量文章排序教程介绍完毕。

