学习 工具

WordPress调用浏览量最高的文章

2020年2月10日

前一段时间给本站文章页面增加了显示浏览量的功能,每个页面都显示被用户点击的次数。

有需要的朋友可以看看这篇文章介绍:不用插件给WordPress文章添加阅读数统计

昨天又在阅读数的基础上又新增了一个小功能,那就是调用当前网站点击量最高的几篇文章。

大家可以在每篇文章的相关阅读地方看到多出了浏览最多的10篇文章。

具体代码:

把以下代码添加到当前主题的functions.php下

function get_most_viewed_format($mode = '', $limit = 10, $show_date = 0, $term_id = 0, $beforedate= '(', $afterdate = ')', $beforecount= '(', $aftercount = ')') {  
  global $wpdb, $post;  
  $output = '';  
  $mode = ($mode == '') ? 'post' : $mode;  
  $type_sql = ($mode != 'both') ? "AND post_type='$mode'" : '';  
  $term_sql = (is_array($term_id)) ? "AND $wpdb->term_taxonomy.term_id IN (" . join(',', $term_id) . ')' : ($term_id != 0 ? "AND $wpdb->term_taxonomy.term_id = $term_id" : '');  
  $term_sql.= $term_id ? " AND $wpdb->term_taxonomy.taxonomy != 'link_category'" : '';  
  $inr_join = $term_id ? "INNER JOIN $wpdb->term_relationships ON ($wpdb->posts.ID = $wpdb->term_relationships.object_id) INNER JOIN $wpdb->term_taxonomy ON ($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id)" : '';  
  // database query  
  $most_viewed = $wpdb->get_results("SELECT ID, post_date, post_title, (meta_value+0) AS views FROM $wpdb->posts LEFT JOIN $wpdb->postmeta ON ($wpdb->posts.ID = $wpdb->postmeta.post_id) $inr_join WHERE post_status = 'publish' AND post_password = '' $term_sql $type_sql AND meta_key = 'views' GROUP BY ID ORDER BY views DESC LIMIT $limit");  
  if ($most_viewed) {  
   foreach ($most_viewed as $viewed) {  
    $post_ID    = $viewed->ID;  
    $post_views = number_format($viewed->views);  
    $post_title = esc_attr($viewed->post_title);  
    $get_permalink = esc_attr(get_permalink($post_ID));  
    $output .= "<li><a href='$get_permalink'>$post_title";  
    if ($show_date) {  
      $posted = date(get_option('date_format'), strtotime($viewed->post_date));  
      $output .= "$beforedate $posted $afterdate";  
    }  
    $output .= "$beforecount $post_views $aftercount</a></li>";  
   }  
  } else {  
   $output = "<li>N/A</li>n";  
  }  
  echo $output;  
}

然后在显示阅读最多文章的地方,使用

<?php get_most_viewed_format(); ?>

这段代码调用即可。

具体需要调用几条可以在上面代码limit后面数值更改就可以。