您想在 WordPress 循环中显示多篇博客文章吗?
WordPress 使用循环处理要在当前页面上显示的每个帖子。它根据它们如何匹配循环标记内的指定条件来格式化它们。
在本文中,我们将展示如何在 WordPress 循环中显示任意数量的帖子。
WordPress 使用循环来显示您的每个帖子。它是 WordPress 主题中使用的 PHP 代码,用于在网页上显示帖子列表。它是 WordPress 代码的重要组成部分,也是大多数查询的核心。
在 WordPress 循环中,有不同的函数运行来显示帖子。但是,开发人员可以通过更改模板标签来自定义每个帖子在循环中的显示方式。
例如,循环中的基本标签将循环显示帖子的标题、日期和内容。您可以添加自定义标签并显示其他信息,例如类别、摘录、自定义字段、作者姓名等。
WordPress 循环还允许您控制每个页面上显示的博客文章的数量。这在设计作者模板时非常有用,因为您可以控制每个循环中显示的帖子数量。
话虽这么说,让我们看看如何向 WordPress 循环添加任意数量的帖子。
通常,您可以从 WordPress 管理面板设置要在循环中显示的帖子数量。
只需从 WordPress 仪表板前往设置 » 阅读即可。默认情况下,WordPress 将显示 10 个帖子。
但是,您可以使用超级循环覆盖该数字,这将允许您在该特定 WordPress 循环中显示任意数量的帖子。
这将允许您自定义页面的显示设置,包括作者个人资料、侧边栏等。
首先,您需要打开一个模板文件,在其中放置帖子,然后只需添加以下循环:
<?php
// if everything is in place and ready, let's start the loop
if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
// to display 'n' number of posts, we need to execute the loop 'n' number of times
// so we define a numerical variable called '$count' and set its value to zero
// with each iteration of the loop, the value of '$count' will increase by one
// after the value of '$count' reaches the specified number, the loop will stop
// *USER: change the 'n' to the number of posts that you would like to display
<?php static $count = 0;
if ( $count == "n" ) {
break;
} else { ?>
// for CSS styling and layout purposes, we wrap the post content in a div
// we then display the entire post content via the 'the_content()' function
// *USER: change to '<?php the_excerpt(); ?>' to display post excerpts instead
<div class="post">
<?php the_title(); ?>
<?php the_content(); ?>
</div>
// here, we continue with the limiting of the number of displayed posts
// each iteration of the loop increases the value of '$count' by one
// the final two lines complete the loop and close the if statement
<?php $count ++;
} ?>
<?php endwhile; ?>
<?php endif; ?>
注意:您需要替换代码的 if ( $count == "n" ) 部分中的“n”值并选择任意数字。
将此代码添加到 WordPress 网站的一种简单方法是使用 WPCode 插件。它是 WordPress 最好的代码片段插件,可帮助您管理自定义代码。
通过使用 WPCode,您无需手动编辑主题模板文件,也无需承担破坏某些内容的风险。该插件会自动为您插入代码。
首先,您需要安装并激活免费的 WPCode 插件。有关更多详细信息,请参阅我们有关如何安装 WordPress 插件的指南。
激活后,您可以从 WordPress 仪表板前往代码片段 » + 添加片段。接下来,您需要选择“添加自定义代码(新代码段)”选项。
之后,只需将我们上面向您展示的 WordPress 循环的自定义代码粘贴到“代码预览”区域即可。
您还需要输入代码的名称,并将“代码类型”设置为“PHP 片段”。
接下来,您可以向下滚动到“插入”部分并选择要运行代码的位置。
默认情况下,WPCode 将在您的 WordPress 网站上的任何位置运行它。但是,您可以将位置更改为特定页面或使用短代码插入代码。
在本教程中,我们将使用默认的“自动插入”方法。
完成后,不要忘记单击顶部的切换按钮使代码处于“活动”状态,然后单击“保存”按钮。 WPCode 现在将在您的 WordPress 博客上部署代码,并在 WordPress 循环中显示指定数量的帖子。
我们希望本文能帮助您了解如何在 WordPress 循环中显示任意数量的帖子。您可能还想查看我们关于如何从 WordPress 循环中排除粘性帖子的指南,以及我们专家精选的商业网站必备 WordPress 插件。
如果您喜欢这篇文章,请订阅我们的 WordPress 视频教程 YouTube 频道。您还可以在 Twitter 和 Facebook 上找到我们。