欢迎您光临自学哈网,只为分享网络知识教程,供大家学习参考!

「自学哈网」WordPress无插件调用浏览次数最多的文章列表

作者 : 自学哈 本文共1925个字,预计阅读时间需要5分钟 2022-11-6 共126人阅读
也想出现在这里? 联系我们

方法/步骤

  1. 首先要使用纯代码统计文章浏览次数。
  2. 将以下模板函数放到自己网站模板的模板函数functions.php里;//获取阅读最多的文章  
    //代码来源:学做网站论坛https://www.xuewangzhan.net/ 
    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;   
    }
  3. 使用以下的代码来调用浏览次数最多的文章列表。<?php get_most_viewed_format(); ?>
本站声明:
本站所有资源来源于网络,分享目的仅供大家学习和交流!如若本站内容侵犯了原著者的合法权益,可联系邮箱976157886@qq.com进行删除。
自学哈专注于免费提供最新的分享知识、网络教程、网络技术的资源分享平台,好资源不私藏,大家一起分享!

自学哈网 » 「自学哈网」WordPress无插件调用浏览次数最多的文章列表
也想出现在这里? 联系我们
© 2022 Theme by - 自学哈网 & WordPress Theme. All rights reserved 浙ICP备2022016594号