主题插件
交易市场

WordPress实现文章根据浏览量从多到少进行排序

WordPress如果想用作新闻资讯类站点无疑是绝佳的选择,现如今,因其简单易用且功能强大的属性为众多新闻资讯站点所青睐,但毕竟核心研发团队是歪果仁,外文才是主要阐述语言,国内开发环境及开发文档缺少,导致中文文档较外文文档相对缺乏。当然,外语专业的人士阅读障碍并不大。那么我们想实现一些改善访客阅读体验的WordPress功能怎么办呢?譬如,根据文章浏览量从多到少进行排序实现最多人看的功能…
我们想要实现最多人看的功能就必须对WordPress的代码风格及编写规范有一定了解,因此仅适合具备一定编程基础的人进行二次开发或者直接使用现成的代码,接下来我将公布自己经过测试并成功实现根据文章浏览量从多到少进行排序的方法希望帮到有需要的人!

将下方代码添加进functions.php外加一个php文件即可实现:

//根据浏览量从多到少进行排序
function get_most_viewed_format($mode = '', $limit = 10, $show_date = 0, $term_id = 0, $beforetitle= '(', $aftertitle = ')', $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_ID).'">'.$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(); ?>

未经允许不得转载:WordPress组织 » WordPress实现文章根据浏览量从多到少进行排序

  • wordpressx
分享到:更多 ()

评论 抢沙发

评论前必须登录!

WordPressX | 主题插件交易市场

发布作品分享经验