您的位置:首页 > 教程笔记 > 综合教程

实现WordPress文章按浏览点击量排序显示(非插件)

2023-11-16 11:00:44 综合教程 35

WordPress建站的时候,需要在侧边栏调用网站中浏览量最多的文章列表。

1.在自己使用的wordpress模板函数文件functions.中加上以下的代码;

/*文章浏览量*/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;  }

2.在显示调用网站浏览量最多文章列表的版块,使用以下的代码进行调用;

<? $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="<? the_permalink(); ?>"><? the_title(); ?></a></li><? endwhile;wp_reset_query();?>

相关推荐