search
HomeWeb Front-endHTML TutorialExplore conditional tags in WordPress: from 1 to 13

探索 WordPress 中的条件标签:从 1 到 13

In the first part of this series, we learned the basics of conditional tags - what they are, how to use them and some scenarios where conditional tags come in handy.

In Part Two we will begin reviewing the 13 conditional tags, and over the course of five articles (including this one) we will complete all 65 conditional tags recorded in the Codex. If you haven't seen part one yet, be sure to check it out.

let us start!

1. Check if we are on the "Blog Post Index Page": is_home()

This Poorly namedConditional tag checks whether the blog post index page is being displayed. In the old days, when WordPress was just a “blogging platform,” “homepage” meant a list of your latest blog posts. But after WordPress evolved into a content management system, the name is_home() became a bit outdated.

Accepted parameters

This conditional tag does not accept any parameters.

Usage example of is_home()

Suppose you want to greet your visitors on your homepage. Here's what you have to do:

<?php

if ( is_home() ) {
    
    _e( 'Welcome to my great blog!', 'translation-domain' );
	
}

?>

2. Check if the current theme is a child theme: is_child_theme()

When developing with WordPress, you may want to check if you are using a child theme. If this is the case, the conditional tag is_child_theme() will help you by returning TRUE or FALSE if a child theme is used or not.

Accepted parameters

This conditional tag does not accept any parameters.

3. Check if a post belongs to a given category: in_category()

In a WordPress project, you may want different categories of posts to behave differently. For example, you might want to add classes to certain posts, or hide them entirely from the general post list. The conditional tag in_category() allows you to identify posts published in one or more categories.

Accepted parameters

This conditional tag has two parameters:

  • $category (array/string, required): Category ID, name, slug, or an array of these. (Default: None)
  • $post (object/integer, optional): The post (ID or object) to check. (Default: current post)

in_category() Usage example

Let's say you have a blog with a lot of categories, one of which is "Announcements", and you want updates to pop up inside other posts, so you want to add a custom class to the post wrapper. Here's what you have to do:

<?php

// Standard Loop stuff.
if ( have_posts() ) {

    while( have_posts() ) {
		
		the_post();

		if ( in_category( '7' ) ) { ?>
			
			<div class="post post-announcement">
			
		<?php } else { ?>
		
			<div class="post">
			
		<?php } ?>
		
				<h2>
    				<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
                </h2>
				
				<div class="post-content">
					<?php the_content(); ?>
				</div>
		
			</div><!-- .post -->

	<?php } 
    	
} else {
	
	echo '<p>' . __( 'Sorry, no posts matched your criteria.', 'translation-domain' ) . '</p>';
	
}

?>

4. Check if "page template" is in use: is_page_template()

Page templates are a feature of WordPress that allows you to choose how certain pages appear. With the conditional tag is_page_template() you can detect whether a certain page template (or any page template) is in use.

Accepted parameters

This conditional tag has only one parameter:

  • $template (String, optional): Name of the template - with extension. (Default: None)

5. Check if the page is an archive page: is_archive()

There are many kinds of archives in WordPress sites: date archives, category archives, tag archives, author archives, custom category archives... But if you want to detect general archive pages, is_archive() is Your friends: Check if the archive page is showing.

Accepted parameters

This conditional tag does not accept any parameters.

Usage examples of is_archive()

Suppose you want to add some text before the post title in an archive page. Here's what you have to do:

<?php

add_filter( 'the_title', 'alter_title_in_archives' );

function alter_title_in_archives( $title ) {

    if ( is_archive() && is_main_query() ) {
    
        return __( 'Archive', 'translation-domain' ) . ' &ndash; ' . $title;
    
    }
    
    return $title;

}

?>

6. Check whether the page is a "date archive" page: is_date()

As I said before, there are many types of archive pages, and date archive is one of them. Date files can be divided into year, month, and day files; but if you want to detect general date archive pages, you can use the is_date() conditional tag.

Accepted parameters

This conditional tag does not accept any parameters.

7. Check if the given widget is in use: is_active_widget()

Creating widgets in WordPress is easy and fun, but we may need to determine if the widget is used on the front end. The conditional tag is_active_widget() does exactly that: it checks whether the widget is being displayed.

Accepted parameters

This conditional tag has four parameters:

  • $callback (字符串,可选):要检查的小部件回调。 (默认:FALSE
  • $widget_id (整数,可选):小部件的 ID。 (默认:无)
  • $id_base (字符串,可选):通过扩展 WP_Widget 创建的小部件的基本 ID。 (默认:无)
  • $skip_inactive (布尔值,可选):是否跳过不活动的小部件。 (默认:TRUE

is_active_widget()的使用示例

假设您的主题中的一个小部件需要 jQuery 才能运行,并且您需要有条件地将其排入队列。这是你要做的:

<?php

// source: http://codex.wordpress.org/Function_Reference/is_active_widget

if ( is_active_widget( false, false, $this->id_base, true ) ) {

    wp_enqueue_script( 'jquery' );

}

?>

8。检查页面是否为单个博客文章页面:is_single()

想要检查用户是否正在访问单个帖子?最流行的条件标签之一 is_single() 可以为您提供帮助。它可以检测任何帖子类型,但附件页面和页面页面除外。如果您指定帖子 ID、帖子标题或帖子标题(或这些内容的数组),您也可以检测特定帖子。

接受的参数

此条件标记只有一个参数:

  • $post (数组/字符串,可选):帖子 ID、标题、slug 或其中的数组。 (默认:无)

9。检查Users表中是否存在Email地址: email_exists()

如果您需要检查电子邮件地址是否在 WordPress 的用户表中,可以使用 email_exists() 条件标签。

此特定条件标记是返回 TRUE 以外内容的三个条件标记之一 - 它返回使用给定电子邮件地址注册的用户 ID。

接受的参数

此条件标记只有一个参数:

  • $email(字符串,可选):要检查的电子邮件地址。 (默认:无)

email_exists() 的使用示例

假设您正在开发一个插件,该插件可以根据用户的电子邮件地址构建电子邮件列表,并允许您使用自定义输入添加和删除更多电子邮件地址,但您希望防止删除属于用户的电子邮件地址。这是你要做的:

<?php

$email_address = get_email_from_some_function();

if ( email_exists( $email_address ) ) {

    wp_die( __( 'Sorry champ, you can\'t delete a user from this list.', 'translation-domain' ) );
    
}

?>

10。检查帖子类型是否分层:is_post_type_hierarchical()

与页面和子页面一样,您可以为 WordPress 中的新自定义帖子类型定义层次结构。条件标签 is_post_type_hierarchical() 让您的代码知道给定的帖子类型是否是分层的。

接受的参数

此条件标记只有一个参数:

  • $post_type (字符串,必需):帖子类型的名称。 (默认:无)

11。检查帖子是否“置顶”:is_sticky()

“置顶帖子”是指无论何时发布,都会保留在帖子列表顶部的帖子。而且——我在这里会有点歧视——他们应该得到与其他普通帖子不同的待遇。因此,如果您想向置顶帖子添加帖子类,或者以不同的方式处理它们,您可以使用 is_sticky() 条件标签让您的代码检测它们。

接受的参数

此条件标记只有一个参数:

  • $post_id (字符串,可选):帖子的 ID。 (默认:无)

is_sticky()的使用示例

假设您正在制作一个主题,并且希望在置顶帖子中显示“置顶”功能区。这是你要做的:

<?php

if ( is_sticky() ) {

    echo '<div class="sticky-ribbon"></div>';
	
}

?>

12。检查是否显示管理面板:is_admin()

让我们知道我们是在前端还是后端,条件标签 is_admin() 是最流行的条件标签之一。顾名思义,is_admin 检查 WordPress 管理面板是否正在显示。

接受的参数

此条件标记不接受任何参数。

13。检查页面是否为“分类档案”页面:is_category()

当您想要检测某些类别存档页面时,可以使用条件标签 is_category()。定义一个类别(或一组类别)作为其参数,您可以检查这些类别的档案是否正在显示。如果您未设置该参数,则当显示任何类别存档页面时,它将返回 TRUE

接受的参数

此条件标记只有一个参数:

  • $category (字符串/数组,可选):类别 ID、标题、slug 或这些的数组。 (默认:无)

is_category()的使用示例

假设您希望在显示“新闻”类别档案时包含不同的侧边栏。这是你要做的:

<?php

if ( is_category() ) {
    
	// Load sidebar-news.php.
	get_sidebar( 'news' );
	
} else {

	// Load sidebar.php.
	get_sidebar();

}

?>

结论

在这一部分中,我们回顾了 WordPress 中记录的 65 个条件标签中的 13 个。在接下来的部分中,我们将讨论剩下的 52 篇文章。如果您有任何问题或意见,请在下面提出 - 如果您喜欢这篇文章,请不要忘记分享!

下一部分见!

The above is the detailed content of Explore conditional tags in WordPress: from 1 to 13. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
From Text to Websites: The Power of HTMLFrom Text to Websites: The Power of HTMLApr 13, 2025 am 12:07 AM

HTML is a language used to build web pages, defining web page structure and content through tags and attributes. 1) HTML organizes document structure through tags, such as,. 2) The browser parses HTML to build the DOM and renders the web page. 3) New features of HTML5, such as, enhance multimedia functions. 4) Common errors include unclosed labels and unquoted attribute values. 5) Optimization suggestions include using semantic tags and reducing file size.

Understanding HTML, CSS, and JavaScript: A Beginner's GuideUnderstanding HTML, CSS, and JavaScript: A Beginner's GuideApr 12, 2025 am 12:02 AM

WebdevelopmentreliesonHTML,CSS,andJavaScript:1)HTMLstructurescontent,2)CSSstylesit,and3)JavaScriptaddsinteractivity,formingthebasisofmodernwebexperiences.

The Role of HTML: Structuring Web ContentThe Role of HTML: Structuring Web ContentApr 11, 2025 am 12:12 AM

The role of HTML is to define the structure and content of a web page through tags and attributes. 1. HTML organizes content through tags such as , making it easy to read and understand. 2. Use semantic tags such as, etc. to enhance accessibility and SEO. 3. Optimizing HTML code can improve web page loading speed and user experience.

HTML and Code: A Closer Look at the TerminologyHTML and Code: A Closer Look at the TerminologyApr 10, 2025 am 09:28 AM

HTMLisaspecifictypeofcodefocusedonstructuringwebcontent,while"code"broadlyincludeslanguageslikeJavaScriptandPythonforfunctionality.1)HTMLdefineswebpagestructureusingtags.2)"Code"encompassesawiderrangeoflanguagesforlogicandinteract

HTML, CSS, and JavaScript: Essential Tools for Web DevelopersHTML, CSS, and JavaScript: Essential Tools for Web DevelopersApr 09, 2025 am 12:12 AM

HTML, CSS and JavaScript are the three pillars of web development. 1. HTML defines the web page structure and uses tags such as, etc. 2. CSS controls the web page style, using selectors and attributes such as color, font-size, etc. 3. JavaScript realizes dynamic effects and interaction, through event monitoring and DOM operations.

The Roles of HTML, CSS, and JavaScript: Core ResponsibilitiesThe Roles of HTML, CSS, and JavaScript: Core ResponsibilitiesApr 08, 2025 pm 07:05 PM

HTML defines the web structure, CSS is responsible for style and layout, and JavaScript gives dynamic interaction. The three perform their duties in web development and jointly build a colorful website.

Is HTML easy to learn for beginners?Is HTML easy to learn for beginners?Apr 07, 2025 am 12:11 AM

HTML is suitable for beginners because it is simple and easy to learn and can quickly see results. 1) The learning curve of HTML is smooth and easy to get started. 2) Just master the basic tags to start creating web pages. 3) High flexibility and can be used in combination with CSS and JavaScript. 4) Rich learning resources and modern tools support the learning process.

What is an example of a starting tag in HTML?What is an example of a starting tag in HTML?Apr 06, 2025 am 12:04 AM

AnexampleofastartingtaginHTMLis,whichbeginsaparagraph.StartingtagsareessentialinHTMLastheyinitiateelements,definetheirtypes,andarecrucialforstructuringwebpagesandconstructingtheDOM.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.