WordPress模板层次03:模板文件中常见代码

模板层次 虚幻 842℃ 0评论

在WordPress模板文件中常见的代码,首先要说的是循环

循环通常以 while 语句开头:

<?php 
if ( have_posts() ) {
	while ( have_posts() ) {/***循环以while语句开始***/
		the_post(); 
		//
		// Post Content here
		//
	} // end while
} // end if
?>

WP Query

循环通常和 WP_Query 一起使用:可以循环遍历给定页面的所有内容。

你可以参考之前的一篇文章:  WordPress开发入门07:WP_Query 自定义循环

WP Query是一个可以添加到循环中的,可定制化搜索更具体的内容的函数。例如,WP Query具有所有以下参数。它可以让我们通过作者,类别,标签,分类,文章或页面,订单,日期查询来对循环进行限制。

[mem]

wp query xuhss.com01 - WordPress模板层次03:模板文件中常见代码

[/mem]

所以,比如说,如果你想通过作者名找到他所写的文章。我们可以添加具有作者姓名参数的WP Query,来搜索那个特定的作者的文章。

$query = new WP_Query( 'author_name=rami' );

这就是wp_query的作用。

get_template_part

接下来要提到的最后一个重要的函数是 get_template_part 。这个函数在WordPress中的作用是包含文件

在WordPress中,通常我们不使用 PHP 的 include 关键字,而是使用 get_template_part

get_template_part接受两个参数。一个是您要查找的文件的主要名称。然后,第二个参数是可选的,它定义了该文件附加的名称。

get_template_part( string $slug, string $name = null )

用法如下:

<?php get_template_part( 'loop', 'index' ); ?>

它将查找名为 loop-index.php 的文件。如果没有,它会按照这个优先级,在文档目录中查找对应的文件。:

wp-content/themes/twentytenchild/loop-index.php
wp-content/themes/twentyten/loop-index.php
wp-content/themes/twentytenchild/loop.php
wp-content/themes/twentyten/loop.php

常见代码在模板文件中的应用

来看一个示例模板,看看其中的一些操作。打开主题下的page.php:

[mem]

common codes xuhss.com01 - WordPress模板层次03:模板文件中常见代码

[/mem]

			<?php
				// Start the Loop.
				while ( have_posts() ) : the_post();/***while循环***/

					// Include the page content template.
					get_template_part( 'content', 'page' );/***get_template_part函数***/

					// If comments are open or we have at least one comment, load up the comment template.
					if ( comments_open() || get_comments_number() ) {
						comments_template();
					}
				endwhile;/***循环在这里结束***/
			?>

 

这里的get_template_part在包含 content-page.php 文件,所以,在主题目录下,找到content-page.php文件。并打开它。

common codes xuhss.com02 - WordPress模板层次03:模板文件中常见代码

通过查看 content-page.php 文件,你应该能够猜出:这个文件才是构建页面主要内容的文件。

 

转载请注明:虚坏叔叔 » WordPress模板层次03:模板文件中常见代码

喜欢 (1)

您必须 登录 才能发表评论!