跳到主要内容

当我们撰写有关如何在WordPress中显示评论最多的帖子时,我们重点介绍了一个插件,可简化初学者的生活。但是,我们的一些用户问我们是否有一种无需安装插件即可显示评论最多的帖子的方法。在本文中,我们将共享一个代码片段,您可以添加该代码片段以显示WordPress中大多数无插件的帖子。

如果您正在学习构建WordPress主题并且不想使用插件,这将非常有用。

请注意,这种方法不适合初学者。如果您对添加代码不满意,则应该查看我们的指南,以了解如何通过使用插件在WordPress中显示评论最多的帖子。如果您正在寻找一种显示最受欢迎的内容的方法,请查看WordPress最受欢迎的帖子插件列表。

让我们开始吧,首先,您需要将以下代码添加到主题或子主题的functions.php文件或特定于站点的插件中。

functionwpb_most_commented_posts() { // start output bufferingob_start();?><ul class="most-commented"><?php // Run WP_Query// change posts_per_page value to limit the number of posts$query= newWP_Query('orderby=comment_count&posts_per_page=10');
//begin loopwhile($query->have_posts()) : $query->the_post(); ?>
<li><a href="<?php the_permalink(); ?>"title="<?php the_title(); ?>"><?php the_title(); ?></a> <span class="wpb-comment-count"><?php comments_popup_link('No Comments;', '1 Comment', '% Comments'); ?></span></li><?php endwhile; // end loop?></ul><?php
// Turn off output buffering $output= ob_get_clean();
//Return output return$output; }// Create shortcodeadd_shortcode('wpb_most_commented', 'wpb_most_commented_posts');
//Enable shortcode execution in text widgetsadd_filter('widget_text', 'do_shortcode');

此代码运行数据库查询,并按评论计数顺序获取10条帖子。我们已经使用了输出缓冲,因此我们可以使用代码创建一个简码。

最后一行启用文本小部件中的短代码执行。现在,为了显示结果,您需要做的就是[wpb_most_commented]在文本小部件或任何WordPress帖子或页面中添加简码。

要在帖子标题旁边显示帖子缩略图,您需要在<li>标题之后添加此行。

<?php the_post_thumbnail(array(40,40)); ?>

数组中使用的值将定义帖子缩略图的自定义大小。您可以对其进行调整以满足您的需求。

要对输出进行样式设置,可以使用主题样式表中的.most-commented.wpb-comment-count类。您可以使用以下CSS入门:

.most-commented li { border-bottom:1pxsolid#eee; padding-bottom:3px; } .most-commented li :after { clear:both;} .most-commented img { padding:3px;margin:3px;float:left;}.wpb_comment_count a, .wpb_comment_count a:active, .wpb_comment_count a:visited, .wpb_comment_count a:hover { color:#FFF;}

我们希望本文能帮助您在未安装新插件的情况下显示WordPress中评论最多的帖子。随意尝试代码和CSS。

回到顶部