在WordPress模板文件中常见的代码,首先要说的是循环。
循环通常以 while 语句开头:
WP Query
循环通常和 WP_Query 一起使用:可以循环遍历给定页面的所有内容。
你可以参考之前的一篇文章: WordPress开发入门07:WP_Query 自定义循环
WP Query是一个可以添加到循环中的,可定制化搜索更具体的内容的函数。例如,WP Query具有所有以下参数。它可以让我们通过作者,类别,标签,分类,文章或页面,订单,日期查询来对循环进行限制。
You must be logged in to view the hidden contents.
所以,比如说,如果你想通过作者名找到他所写的文章。我们可以添加具有作者姓名参数的WP Query,来搜索那个特定的作者的文章。
这就是wp_query的作用。
get_template_part
接下来要提到的最后一个重要的函数是 get_template_part 。这个函数在WordPress中的作用是包含文件。
在WordPress中,通常我们不使用 PHP 的 include 关键字,而是使用 get_template_part :
get_template_part接受两个参数。一个是您要查找的文件的主要名称。然后,第二个参数是可选的,它定义了该文件附加的名称。
用法如下:
它将查找名为 loop-index.php 的文件。如果没有,它会按照这个优先级,在文档目录中查找对应的文件。:
常见代码在模板文件中的应用
来看一个示例模板,看看其中的一些操作。打开主题下的page.php:
You must be logged in to view the hidden contents.
这里的get_template_part在包含 content-page.php 文件,所以,在主题目录下,找到content-page.php文件。并打开它。
通过查看 content-page.php 文件,你应该能够猜出:这个文件才是构建页面主要内容的文件。