WordPress按热门文章排序方法,设置文章浏览量排序

网站搭建 z197 1508次浏览 已收录 用手机观看

记录下,按阅读量排序的热门文章的方法。

打开wordpress网站后台

在functions.php文件中中添加以下代码;

/*文章浏览量*/
function 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', 'record_visitors');
/// 函数名称:post_views
/// 函数作用:取得文章的阅读次数
function post_views($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;
}

在需要调用按浏览量排序的热门文章位置,使用以下的代码进行调用文章列表;

<ul>
<?php $args=array(
'meta_key' => 'post_views_count',
'orderby' => 'meta_value_num',
'posts_per_page'=>10,
'order' => 'DESC'
);
query_posts($args);  while (have_posts()) : the_post();?>
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a><span class="kc-view fright">浏览:<?php setPostViews(get_the_ID()); echo number_format(getPostViews(get_the_ID())); ?></span></li>
<?php endwhile;wp_reset_query();?>
</ul>

这样就可以调用出用户浏览最多的10篇文章了。