个人工具
名字空间
变换
操作

WordPress:Conditional Tags

来自站长百科
2008年7月12日 (六) 07:36Fludlen (讨论 | 贡献)的版本
跳转到: 导航, 搜索

目录

Introduction

介绍

The Conditional Tags can be used in your Template files to change what content is displayed and how that content is displayed on a particular page depending on what conditions that page matches. For example, you might want to display a snippet of text above the series of posts, but only on the main page of your blog. With the [[WordPress:#The Main Page|is_home()]] Conditional Tag, that task is made easy.

条件式标签可以用在你的模板文件中,更改显示的内容,并且根据网页匹配什么样的情况,更改内容在一个网页上的显示方式。例如,你可能想要在一些文章的上面,在你的博客的主页上显示文章的摘录。拥有[[WordPress:#The Main Page|is_home()]]条件式标签,做到这一点,变得非常简单。

Note the close relation these tags have to WordPress' WordPress:Template Hierarchy.

注意这些标签与WordPress的模板层级之间的密切关系。

The Conditions For...

条件关于...

All of the Conditional Tags test to see whether a certain condition is met, and then returns either TRUE or FALSE. The conditions under which various tags output TRUE is listed below. Those tags which can accept parameters are so noted.

所有的条件式标签测试看看是否符合某个条件,然后返回正确或者错误。不同的标签输出为正确的条件列在了下面。能够接受参数的标签非常又名。

The Main Page

主页

is_home() 
When the main blog page is being displayed. (Wordpress 2.1 handles this function differently than prior versions. See static Front Page.)
is_home() 
显示主要的博客网页的时候(WordPress2.1版本与先前的版本处理这个函数的方式不同。请看看

Note: If you select a static Page as your frontpage (see below), this tag will be applied to your "posts page".

注:如果你选择了一个静态的网页作为你的首页(请看看下面的),这个标签会应用到你的"文章 页面"。

The Front Page

首页

is_front_page() 
When it is the front of the site displayed, whether it is posts or a Page. Returns true when the main blog page is being displayed and the 'Settings->Reading->Front page displays' is set to "Your latest posts", or when 'Settings->Reading->Front page displays' is set to "A static page" and the "Front Page" value is the current Page being displayed. Note: this tag was added at WordPress:Version 2.5.
is_front_page() 
显示站点的首页的时候,不管是文章还是网页。显示主要的博客页面的时候,返回正确的,而且'设置->阅读->显示首页'设置为"你最近的文章",或者当'设置->阅读->显示首页'设置为"一个静态网页" 而且"首页"参数值是当前显示的网页。注:这个标签是在2.5版本中添加的。

The Administration Panels

管理面板

is_admin()
When the Dashboard or the administration panels are being displayed.
is_admin()
Dashboard或者管理面板正在显示的时候。

A Single Post Page

一个单独的文章网页

is_single() 
When any single Post page is being displayed.
is_single() 
显示任何只有一篇文章的网页的时候。
is_single('17') 
When Post 17 is being displayed as a single Post.
is_single('17') 
第17篇文章作为一篇单一的文章显示的时候。
is_single('Irish Stew') 
When the Post with Title "Irish Stew" is being displayed as a single Post.
is_single('Irish Stew') 
拥有标题"土豆洋葱煮肉"的文章作为一篇单一的文章显示的时候。
is_single('beef-stew') 
When the Post with Post Slug "beef-stew" is being displayed as a single Post.
is_single('beef-stew') 
拥有Post Slug"beef-stew"的文章作为一篇单一的文章,正在显示的时候。
is_single(array(17,'beef-stew','Irish Stew')) 
Returns true when the single post being displayed is either post ID 17, or the post_name is "beef-stew", or the post_title is "Irish Stew". Note: the array ability was added at WordPress:Version 2.5.
is_single(array(17,'beef-stew','Irish Stew')) 
当显示的单篇文章是文章ID17,或者post_name是"beef-stew",或者post_title是"Irish Stew"的时候,返回正确的。注:array ability是在2.5版本中添加的。

Any Page Containing Posts

任何包含有文章的网页

comments_open()
When comments are allowed for the current Post being processed in the WordPress Loop.
comments_open()
允许对正在WordPress Loop|The Loop中进行处理的当前文章,进行评论的时候。
pings_open()
When pings are allowed for the current Post being processed in the WordPress Loop.
pings_open()
允许对正在WordPress Loop|The Loop中进行处理的当前文章,进行pings的时候。

A PAGE Page

A PAGE Page

This section refers to WordPress WordPress:Pages, not any generic webpage from your blog.

这个部分指的是WordPress 网页,而不是博客中的任何网页。

is_page() 
When any Page is being displayed.
is_page() 
正在显示任何网页的时候。
is_page('42') 
When Page 42 (ID) is being displayed.
is_page('42') 
正在显示网页42(ID)的时候。
is_page('About Me And Joe') 
When the Page with a post_title of "About Me And Joe" is being displayed.
is_page('关于我和Joe') 
显示拥有一个post_title"关于我和Joe"的网页
is_page('about-me') 
When the Page with a post_name (slug) of "about-me" is being displayed.
is_page('about-me') 
显示拥有post_name (slug) "about-me"的网页
is_page(array(42,'about-me','About Me And Joe')) 
Returns true when the Pages displayed is either post ID 42, or post_name "about-me", or post_title "About Me And Joe". Note: the array ability was added at WordPress:Version 2.5.
is_page(array(42,'about-me','关于我和 Joe')) 
当显示的网页是文章ID42,或者post_name "about-me",或者post_title "关于我和 Joe"时,返回正确的。注:array ability是在2.5版本中添加的。

Testing for sub-Pages

测试子网页

There is no is_subpage() function yet, but you can test this with a little code:

还没有is_subpage()函数,但是你可以用较少的代码测试这个:

<?php
// Get $post if you're inside a function
global $post;

if (is_page() && $post->post_parent ) {
	// This is a subpage
} else {
	// This is not a subpage
}
?>


<?php
// 如果你在一个函数的内部,得到$文章
global $post;

if (is_page() && $post->post_parent ) {
	// 这是个子网页
} else {
	// 这不是个子网页
}
?>

If you need to test whether this is a particular page OR a child of that page (e.g. to present a different banner on different sections of a page-based site), get the parent page IDs from the back-end, then use code like this:

如果你需要测试这是不是个特别的网页还是子网页(例如在以网页为基础的网站上的不同部分呈现不同的标语),从后端得到当前网页ID,然后使用下面的代码:

<?php

if 	(is_page(about) || $post->post_parent=="2") { 
	$bannerimg="home.jpg"; 
} elseif (is_page(learning) || $post->post_parent=="56") {	
	$bannerimg="teaching.jpg"; 
} elseif (is_page(admissions) || $post->post_parent=="15") { 
	$bannerimg="admissions.jpg";	
} else { 
	$bannerimg="home.jpg" ; // Fall-through  
}	

?>


<?php

if 	(is_page(about) || $post->post_parent=="2") { 
	$bannerimg="home.jpg"; 
} elseif (is_page(learning) || $post->post_parent=="56") {	
	$bannerimg="teaching.jpg"; 
} elseif (is_page(admissions) || $post->post_parent=="15") { 
	$bannerimg="admissions.jpg";	
} else { 
	$bannerimg="home.jpg" ; // Fall-through  
}	

?>

Is a Page Template

是网页模板

Beginning with WordPress:Version 2.5 this allows you to determine whether or not you are in a page template or if a specific page template is being used.

2.5版本开始,这能够使你决定你是否在网页模板上或者你是不是正在使用一个特别的网页模板。

is_page_template() 
Is a Page Template being used?
is_page_template('about.php') 
Is Page Template 'about' being used? Note that unlike with other conditionals, if you want to specify a particular Page Template, you need to use the filename, such as about.php or my_page_template.php.


is_page_template() 
正在使用网页模板 吗?
is_page_template('about.php') 
正在使用 网页模板 '关于' 吗? 注意与其它的条件不同,如果你想要规定一个特别的网页模板,你需要使用文件名,例如about.php或者my_page_template.php。

A Category Page

类别网页

is_category() 
When any Category archive page is being displayed.
is_category() 
显示任何类别归档网页的时候。
is_category('9') 
When the archive page for Category 9 is being displayed.
is_category('9') 
显示关于类别9的归档网页的时候。
is_category('Stinky Cheeses') 
When the archive page for the Category with Name "Stinky Cheeses" is being displayed.
is_category('发臭的干酪') 
显示名称是"发臭的干酪"的类别的归档网页的时候。
is_category('蓝纹奶酪') 
显示类别Slug"蓝纹奶酪"的归档网页的时候。
is_category(array(9,'blue-cheese','发臭的奶酪')) 
显示的文章的类别是term_ID 9,或者 slug "蓝纹奶酪", 或者 名称 "发臭的干酪"的时候,返回正确的。 注: the array ability 是在 2.5版本中添加的。
in_category('5') 
Returns true if the current post is in the specified category id. read more

Note: Be sure to check your spelling when testing, "is" and "in" are a big difference.

in_category('5') 
如果当前文章是特别规定的类别id内,返回正确的。阅读更多的 注:测试的时候,要确定检查好了拼写,"is" 和"in"是根本的两码事。

See also [[WordPress:#Any Archive Page|is_archive()]] and WordPress:Category Templates.

也看看[[WordPress:#Any Archive Page|is_archive()]]类别模板

A Tag Page

标签网页

is_tag() 
When any Tag archive page is being displayed.
is_tag() 
显示任何标签归档网页的时候。
is_tag('mild') 
When the archive page for tag with the slug of 'mild' is being displayed.
is_tag('mild') 
显示带有slug'mild'的标签的归档网页的时候。
is_tag(array('sharp','mild','extreme')) 
Returns true when the tag archive being displayed has a slug of either "sharp", "mild", or "extreme". Note: the array ability was added at WordPress:Version 2.5.
is_tag(array('sharp','mild','extreme')) 
当显示的标签归档拥有一个slug是"sharp", "mild",或者 "extreme"的时候,返回正确的。注:array ability是在2.5版本时,添加的。

See also [[WordPress:#Any Archive Page|is_archive()]] and WordPress:Tag Templates.

也看看[[WordPress:#Any Archive Page|is_archive()]]标签模板

An Author Page

作者网页

is_author() 
When any Author page is being displayed.
is_author() 
显示任何作者网页的时候。
is_author('4') 
When the archive page for Author number (ID) 4 is being displayed.
is_author('4') 
显示作者号(ID)4的归档网页的时候。
is_author('Vivian') 
When the archive page for the Author with Nickname "Vivian" is being displayed.
is_author('Vivian') 
显示作者昵称名为"Vivian"的归档网页的时候。
is_author('john-jones') 
When the archive page for the Author with Nicename "john-jones" is being displayed.
is_author('john-jones') 
显示作者昵称"john-jones"的归档网页的时候。
is_author(array(4,'john-jones','Vivian')) 
When the archive page for the author is either user ID 4, or user_nicename "john-jones", or nickname "Vivian". Note: the array ability was added at WordPress:Version 2.5.
is_author(array(4,'john-jones','Vivian')) 
作者是用户ID4或者user_nicename "john-jones", 或者nickname "Vivian"时候的归档网页。注:array ability是在2.5版本中添加的。

See also [[WordPress:#Any Archive Page|is_archive()]] and WordPress:Author Templates.

也看看[[WordPress:#Any Archive Page|is_archive()]]作者模板

A Date Page

日期网页

is_date() 
When any date-based archive page is being displayed (i.e. a monthly, yearly, daily or time-based archive).
is_date() 
显示任何以日期为基础的归档网页的时候(例如,按月,按年,按日或者以时间为基础的归档)。
is_year() 
When a yearly archive is being displayed.
is_year() 
显示某一年的归档。
is_month() 
When a monthly archive is being displayed.
is_month() 
显示某一月的归档。
is_day() 
When a daily archive is being displayed.
is_day() 
显示某一天的归档的时候。
is_time() 
When an hourly, "minutely", or "secondly" archive is being displayed.
is_time() 
显示某个小时,"某分",或者"某秒"的归档的时候。

See also [[WordPress:#Any Archive Page|is_archive()]]. 也看看:[[WordPress:#Any Archive Page|is_archive()]]

Any Archive Page

任何归档网页

is_archive() 
When any type of Archive page is being displayed. Category, Author and Date based pages are all types of Archives.
is_archive() 
显示任何类型的归档网页的时候。以类别,作者和日期为基础的网页是各种类型的归档。

A Search Result Page

搜索结果网页

is_search() 
When a search result page archive is being displayed.
is_search() 
显示搜索结果网页归档的时候。

A 404 Not Found Page

404 没有找到网页

is_404() 
When a page displays after an "HTTP 404: Not Found" error occurs.
is_404() 
在出现"HTTP 404: 没有发现"错误的之后,显示的网页。

A Paged Page

A Paged Page

is_paged() 
When the page being displayed is "paged". This refers to an archive or the main page being split up over several pages. This does not refer to a Post or Page whose content has been divided into pages using the <!--nextpage--> QuickTag.
is_paged() 
当显示的网页是"paged"。这指的是归档或者主页被分成了几个网页。这并不指一篇文章或者网页使用<!--nextpage--> QuickTag被分成了几个网页。

An Attachment

=== 附属装置===
is_attachment() 
When an attachment document to a post or Page is being displayed. An attachment is an image or other file uploaded through the post editor's upload utility. Attachments can be displayed on their own 'page' or template. For more information, see WordPress:Using Image and File Attachments.
is_attachment() 
显示文章或者网页的附属文件的时候。附属文件是一个图像或者通过文章编辑的上传功能上传的其它的文件。附属文件可以在自身的'网页'或者模板上显示。更多的信息,请看看使用图像和文件附属装置

A Syndication

联合供稿

is_feed() 
When the site requested is a Syndication. This tag is not typically used by users; it is used internally by WordPress and is available for Plugin Developers.
is_feed() 
需要的站点是Syndication。通常用户不使用这个标签;由WordPress内部使用,而且插件开发人员也可以得到这个标签。

A Trackback

A Trackback

is_trackback() 
When the site requested is WordPress' hook into its Trackback engine. This tag is not typically used by users; it is used internally by WordPress and is available for Plugin Developers.
is_trackback() 
需要的站点,WordPress的hook进入Trackback引擎的时候。通常用户不使用这个标签;由WordPress内部使用,而且插件开发人员也可以得到这个标签。

A Preview

预览

is_preview() 
When a single post being displayed is viewed in Draft mode.
is_preview() 
以草稿样式浏览显示的单篇文章的时候。

Has An Excerpt

有一个摘录

!empty($post->post_excerpt) 
There is no built-in way to check if a post has an excerpt, but you can use the above code in the same way. Remove the '!' to emulate 'has_no_excerpt'.
!empty($post->post_excerpt) 
没有内置的方法,检查一篇文章是否有摘录,但是你可以用同样的方法使用上传的代码。移除'!',效仿'has_no_excerpt'。

Working Examples

Working 例子

Here are working samples to demonstrate how to use these conditional tags.

下面是working例子,用来阐述怎样使用这些条件式标签。

Single Post

单篇文章

This example shows how to use is_single() to display something specific only when viewing a single post page:

这个例子显示怎样使用is_single(),在浏览只有一篇文章的网页的时候,显示一些特别的内容。

if (is_single())
{
     echo 'This is just one of many fabulous entries in the ' . single_cat_title() . ' category!';
}


if (is_single())
{
     echo '这只是 ' . single_cat_title() 中其中的一篇预言文章。 ' category!';
}

Date-Based Differences

以日期为基础的差异

If someone browses our site by date, let's distinguish posts in different years by using different colors:

如果有人根据日期浏览我们的站点,我们可以使用不同的颜色,将不同的年份的文章,区分开来。

<?php
// this starts The Loop
if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<h2 id="post-<?php the_ID(); ?>">
<a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title(); ?>">
<?php the_title(); ?></a></h2>
<small><?php the_time('F jS, Y') ?> <!-- by <?php the_author() ?> --></small>

<?php
// are we showing a date-based archive?
if (is_date())
{
     if (date('Y') != get_the_date('Y'))
     {
          // this post was written in a previous year
          // so let's style the content using the "oldentry" class
          echo '<div class="oldentry">';
     } else {
          echo '<div class="entry">';
     }
} else {
     echo '<div class="entry">';
}
the_content('Read the rest of this entry »'); 
?>
</div>








<?php
// 这开始了 Loop
if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<h2 id="post-<?php the_ID(); ?>">
<a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title(); ?>">
<?php the_title(); ?></a></h2>
<small><?php the_time('F jS, Y') ?> <!-- by <?php the_author() ?> --></small>

<?php
//我们正在显示以日期为基础的归档吗?
if (is_date())
{
     if (date('Y') != get_the_date('Y'))
     {
          // 这篇文章是前年写的
          // 让我们使用 "旧的文章" 级别来设计内容
          echo '<div class="oldentry">';
     } else {
          echo '<div class="entry">';
     }
} else {
     echo '<div class="entry">';
}
the_content('阅读这篇文章的其余部分 »'); 
?>
</div>






Variable Sidebar Content

不同的工具条内容

This example will display different content in your sidebar based on what page the reader is currently viewing.

根据读者现在在浏览哪个网页,这个例子会在你的工具条中显示不同的内容。

<!-- begin sidebar -->
<div id="sidebar">
<?php
// let's generate info appropriate to the page being displayed
if (is_home()) {
        // we're on the home page, so let's show a list of all top-level categories
        echo "<ul>";
        wp_list_cats('optionall=0&sort_column=name&list=1&children=0');
        echo "</ul>";
} elseif (is_category()) {
        // we're looking at a single category view, so let's show _all_ the categories
         echo "<ul>";
        wp_list_cats('optionall=1&sort_column=name&list=1&children=1&hierarchical=1');
        echo "</ul>";
} elseif (is_single()) {
        // we're looking at a single page, so let's not show anything in the sidebar
} elseif (is_page()) {
        // we're looking at a static page.  Which one?
        if (is_page('About')) {
             // our about page.
             echo "<p>This is my about page!</p>";
        } elseif (is_page('Colophon')) {
             echo "<p>This is my colophon page, running on WordPress " . bloginfo('version') . "</p>";
        } else {
              // catch-all for other pages
              echo "<p>Vote for Pedro!</p>";
        }
} else {
        // catch-all for everything else (archives, searches, 404s, etc)
        echo "<p>Pedro offers you his protection.</p>";
} // That's all, folks!
?>
<form id="searchform" method="get" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<div>
<input type="text" name="s" id="s" size="15" />
<input type="submit" value="<?php _e('Search'); ?>" />
</div>
</form>

</div>
<!-- end sidebar -->




<!-- begin sidebar -->
<div id="sidebar">
<?php
// 让我们提供与正在显示的文章相关的信息l
if (is_home()) {
        //我在在主页上,显示最高级别的类别的列表        echo "<ul>";
        wp_list_cats('optionall=0&sort_column=name&list=1&children=0');
        echo "</ul>";
} elseif (is_category()) {
        // 我们正在查看一个单一的类别,让我们show _all_ the 类别
         echo "<ul>";
        wp_list_cats('optionall=1&sort_column=name&list=1&children=1&hierarchical=1');
        echo "</ul>";
} elseif (is_single()) {
        // 我们在浏览单一的网页,在工具条上不显示任何内容
} elseif (is_page()) {
        // 我们在浏览一个静态的网页。哪一个?
        if (is_page('About')) {
             //我们的关于网页。
             echo "<p>这是我的关于网页!</p>";
        } elseif (is_page('Colophon')) {
             echo "<p>这是我的最后一个网页, 在WordPress上运行 " 。 bloginfo('version') . "</p>";
        } else {
              // 抓取所有的其它网页。
              echo "<p>Vote for Pedro!</p>";
        }
} else {
        //抓取所有的其它内容 (归档,搜索, 404s, 等等)
        echo "<p>Pedro向你提供保护。</p>";
} // 伙计,就这麽多!
?>
<form id="searchform" method="get" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<div>
<input type="text" name="s" id="s" size="15" />
<input type="submit" value="<?php _e('Search'); ?>" />
</div>
</form>

</div>
<!—结束工具条-->







Helpful 404 page

有用的404页面

When a visitor gets a 404 error page, it can be intimidating, and unhelpful. Using Wordpress, you can take the edge off a 404 and make it helpful to users, and yourself, too, by emailing whenever the user clicks a link to a non-existent page. If you use this, don't forget o

访客遇到一个404错误网页的时候,这个网页可能不起作用。使用WordPress,你可以减少404的错误,使得用户和你自己能够使用这个网页,当用户点击一个链接,链接到不存在的网页的时候,可以发送电子邮件。如果你也使用这个方法,不要忘记o

<p>You 
<?php
#some variables for the script to use
#if you have some reason to change these, do.  but wordpress can handle it
$adminemail = get_bloginfo('admin_email'); #the administrator email address, according to wordpress
$website = get_bloginfo('url'); #gets your blog's url from wordpress
$websitename = get_bloginfo('name'); #sets the blog's name, according to wordpress

  if (!isset($_SERVER['HTTP_REFERER'])) {
    #politely blames the user for all the problems they caused
        echo "tried going to "; #starts assembling an output paragraph
	$casemessage = "All is not lost!";
  } elseif (isset($_SERVER['HTTP_REFERER'])) {
    #this will help the user find what they want, and email me of a bad link
	echo "clicked a link to"; #now the message says You clicked a link to...
        #setup a message to be sent to me
	$failuremess = "A user tried to go to $website"
        .$_SERVER['REQUEST_URI']." and received a 404 (page not found) error. ";
	$failuremess .= "It wasn't their fault, so try fixing it.  
        They came from ".$_SERVER['HTTP_REFERER'];
	mail($adminemail, "Bad Link To ".$_SERVER['REQUEST_URI'],
        $failuremess, "From: $websitename <noreply@$website>"); #email you about problem
	$casemessage = "An administrator has been emailed 
        about this problem, too.";#set a friendly message
  }
  echo " ".$website.$_SERVER['REQUEST_URI']; ?> 
and it doesn't exist. <?php echo $casemessage; ?>  You can click back 
and try again or search for what you're looking for:
  <?php include(TEMPLATEPATH . "/searchform.php"); ?>
</p>







<p>You 
<?php
#some variables for the script to use
#if you have some reason to change these, do.  but wordpress can handle it
$adminemail = get_bloginfo('admin_email'); #the administrator email address, according to wordpress
$website = get_bloginfo('url'); #gets your blog's url from wordpress
$websitename = get_bloginfo('name'); #sets the blog's name, according to wordpress

  if (!isset($_SERVER['HTTP_REFERER'])) {
#客气地责备制造了这些问题的用户
        echo "tried going to "; #开始组成一个产出段落
	$casemessage = "所有的内容都没有丢失!";
  } elseif (isset($_SERVER['HTTP_REFERER'])) {
#这回帮助用户发现他们想要什么,如果发现一个不好的链接,请给我发送电子邮件
	echo "点击链接到"; #现在消息显示,你点击链接到...
        #设置一个消息发送给我
	$failuremess = "一名用户试着进入$website"
        .$_SERVER['REQUEST_URI']." 而且遇到a 404 (没有发现网页) 错误。 ";
	$failuremess .= "如果不是他们的错误,试着解决这个错误。 
        They came from ".$_SERVER['HTTP_REFERER'];
	mail($adminemail, "Bad Link To ".$_SERVER['REQUEST_URI'],
        $failuremess, "From: $websitename <noreply@$website>"); #email you about problem
	$casemessage = "发送一封邮件给管理员,内容关于这个问题。";#set a friendly message
  }
  echo " ".$website.$_SERVER['REQUEST_URI']; ?> 
and it doesn't exist. <?php echo $casemessage; ?>  你可以点击返回并且再试试搜索你要找的内容:
  <?php include(TEMPLATEPATH . "/searchform.php"); ?>
</p>


Dynamic Menu Highlighting

突出动态的菜单

The WordPress:Dynamic Menu Highlighting article discusses how to use the conditional tags to enable highlighting of the current page in a menu.

突出动态菜单的文章阐述怎样使用条件式标签,突出菜单中的当前的网页。

External Ressources

外部资源


Template:No Param Tag Footer

Go to Template Tag index