WordPress 博客非插件显示最多评论文章列表的方法

WordPress教程 6075

热门文章可分为浏览最多的文章和被评论最多的文章,WordPress博客小工具里没有显示最多评论文章的小工具,博客吧目前也没有发现WordPress博客有最多评论文章的调用标签,所以实现这个功能很多博主选择了插件,本篇博客吧介绍的是非插件实现显示最多评论文章列表。

显示最多评论文章列表的方法:

  1. 登陆博客后台,点击“外观”选项卡下的“编辑”选项进入主题编辑界面
  2. 选择functions.php文件,在<?php和?>之间插入以下函数代码
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    
    function most_popular_posts($no_posts = 10, $before = '<li>', $after = '</li>', $show_pass_post = false, $duration='') {
    //定制参数,可以自己修改相关参数,以便写样式
    global $wpdb;
    $request = "SELECT ID, post_title, COUNT($wpdb->comments.comment_post_ID) AS 'comment_count' FROM $wpdb->posts, $wpdb->comments";
    //在数据库里选择所需的数据
    $request .= " WHERE comment_approved = '1' AND $wpdb->posts.ID=$wpdb->comments.comment_post_ID AND post_status = 'publish'";
    //筛选数据,只统计公开的文章
    if(!$show_pass_post) $request .= " AND post_password =''";
    if($duration !="") { $request .= " AND DATE_SUB(CURDATE(),INTERVAL ".$duration." DAY) < post_date ";
    }
    $request .= " GROUP BY $wpdb->comments.comment_post_ID ORDER BY comment_count DESC LIMIT $no_posts";
    //按评论数排序
    $posts = $wpdb->get_results($request);
    $output = '';
    if ($posts) {
    foreach ($posts as $post) {
    $post_title = stripslashes($post->post_title);
    $comment_count = $post->comment_count;
    $permalink = get_permalink($post->ID);
    $output .= $before . '<a href="' . $permalink . '" title="' . $post_title.'">' . $post_title . '</a> (' . $comment_count.')' . $after;
    }
    //输出文章列表项
    } else {
    $output .= $before . "None found" . $after;
    //没有文章时则输出
    }
    echo $output;
    }
  3. 在要显示最多评论文章列表的地方添加调用代码即可
    1
    2
    3
    
    <ul>
    <?php most_popular_posts(); ?>
    </ul>

提醒:代码来自互联网,非博客吧原创!

精品推荐: