1 WordPress升级5.8之后获取最新评论的代码失效问题解决

手欠点了升级WordPress5.8之后今天发现主题中获取最新评论的功能失效了,之前主题中获取最新评论的代码如下:

/* 之前主题的旧代码,在升级为WordPress5.8之后失效 */
function suxingme_newcomments_old( $limit,$outpost,$outer ){
$limit = $limit ? $limit : 5;
$outpost = $outpost ? $outpost : 0;
$outer = $outer ? $outer : 1;
$output='';
global $wpdb;
    $sql = "SELECT DISTINCT ID, post_title, post_password, comment_ID, comment_post_ID, comment_author,user_id, comment_date_gmt, comment_approved,comment_author_email, comment_type,comment_author_url, SUBSTRING(comment_content,1,40) AS com_excerpt FROM $wpdb->comments LEFT OUTER JOIN $wpdb->posts ON ($wpdb->comments.comment_post_ID = $wpdb->posts.ID) WHERE comment_post_ID!='".$outpost."' AND user_id!='".$outer."' AND comment_approved = '1' AND comment_type = '' AND post_password = '' ORDER BY comment_date_gmt DESC LIMIT $limit";
    $comments = $wpdb->get_results($sql);
foreach ($comments as $comment) {

$output .= "<li><div class='message'><a href=\"" . get_permalink($comment->ID) ."#comment-" . $comment->comment_ID . "\" title=\"发表在: " .$comment->post_title . "\" class='comment_t'>". strip_tags($comment->com_excerpt)."</a></div><div class='clearfix meta'><div class='avatar'>".get_avatar( $comment )."</div><a href=\"" . get_permalink($comment->ID) ."#comment-" . $comment->comment_ID . "\" title=\" 在: " .$comment->post_title . "\" class='link'>".strip_tags($comment->comment_author)." 评 " .$comment->post_title . "</a></div></li>";
}


$output = convert_smilies($output);
echo $output;
};

经过在本地调试之后以及查询官方的文档之后,决定使用get_comments函数替换上述使用sql语句查询数据库获取最新评论的方式,修改后的代码如下:

/* 修改于2021年8月14日,修复在升级WordPress5.8之后最新评论显示失效的问题 */
function suxingme_newcomments( $limit,$outpost,$outer ){
    $limit = $limit ? $limit : 5;
    $output='';
    $comments = get_comments('status=approve&number='.$limit.'');
    foreach ($comments as $comment) {

        $output .= "<li><div class='message'><a href=\"" . get_permalink($comment->ID) ."#comment-" . $comment->comment_ID . "\" title=\"发表在: " .$comment->post_title . "\" class='comment_t'>". strip_tags($comment->comment_content)."</a></div><div class='clearfix meta'><div class='avatar'>".get_avatar( $comment )."</div><a href=\"" . get_permalink($comment->ID) ."#comment-" . $comment->comment_ID . "\" title=\" 在: " .$comment->post_title . "\" class='link'>".strip_tags($comment->comment_author)." 评 " .$comment->post_title . "</a></div></li>";
    }


    $output = convert_smilies($output);
    echo $output;
};

修改完成之后,获取最新评论的功能终于正常了!