WordPress Theme Development Tutorial Manual - Conditional Tag Functions
Conditional functions can be used in WordPress templates, usually as an if/else condition to determine whether the current page meets a certain condition, and then display the corresponding content according to the judgment result.
This function generallyReturns a boolean valueIf the return value is true, the code following if is executed, and if false, the code following else is executed.
In the following sample code, we use the is_user_logged_in() function to determine whether the user is logged in, and then according to the user's logged-in status, display the corresponding greeting.
if ( is_user_logged_in() ).
echo 'Welcome, registered user! ;
else.
echo 'Welcome, please register a user!' endif; echo 'Welcome, please register a user!
endif.
Where to use conditional labeling functions
Before you can use a conditional function, the information that the conditional function uses to make a judgment must have already been fetched from the database, i.e. the WordPress query has already been run. If you use a conditional function before WordPress gets the data, the conditional function will not work.
We can use conditional functions in three ways:
- existTemplate filesUse in.
- Create a function in functions.php and call it in the template file
- Create a function in functions.php and use it in an action or filter.
Conditional Labeling Functions Explained
Here are the ones we can useReturns true of conditional functions, some of which can take arguments.
homepage
This function returns true if the current page is the home page of the website. If the home page is set to "Static Page" in the Reading Settings, this function only returns true in the page set to "Your Latest Posts".
This function returns true if the current page is the first page of the website, regardless of whether it is the "latest article" or "static page" set in the reading settings.
That is, the function returns true in the following two cases
- Blog Home
- "Settings -> Reading -> Home Display " is set to "Your latest articles"
or
- "Settings -> Reading -> Home Display " is set to " A static page "
- The current display is the static page selected above
management back office
This function returns true when we are on a dashboard or backend page.
Single article page
Returns true if the current page is an article detail page (or attachment or custom article type detail page), or false if it is a page.
is_single ('17')
is_single() You can also use the article ID and other article parameters to determine if it is a specific article. The above function returns true when the article ID is 17.
is_single('Hello World')
The parameter can also be the title of the article. If the current page is an article with the title "Hello World", the above function returns true.
is_single('hello-world')
The parameter can also be an article alias. The above function returns true if the current page is an article with the alias "hello-world".
is_single( array( 17, 'beef-stew', 'Irish Stew' ) )
The arguments to this function can also be an array whose elements can be article IDs, article aliases, and article names.
Note: The arguments to this function do not distinguish between article IDs, aliases, or titles. Assuming we pass 17 as an argument, the function returns true when the article ID is 17 or the alias is 17.
Article details, pages, or attachment pages
This function returns true if any of is_single, is_page, and is_attachment are true, and accepts the name of a file type as an argument to determine if it is an article detail page for a particular article type.
sticky (of an online forum)
This function returns true if the current article is set to top in the edit screen, and in a loop, it can take an article ID as an argument to determine whether an article is top or not.
is_sticky ('17')
Determines if the article with ID 17 is the top article. This parameter is set automatically when used in the article loop and can be omitted.
Article Type
We can do this through the get_post_type() to test whether the current article is an article of a certain article type. Strictly speaking, this is not a conditional function, but we can compare the result with the article type we need to determine, as follows:
if ('book' == get_post_type())...
Used to determine if an article type has been registered.
Is the article type graded
is_post_type_hierarchical($post_type)
This function is used to determine whether a post type is hierarchical, for example, WordPress default page with parent and child pages means that the post type is hierarchical, then the following function will return true:
is_post_type_hierarchical ('page')
Article type archive page (list page)
Used to determine if the current page is a list page of the article type.
is_post_type_archive($post_type)
This function accepts an article type name as an argument to determine if the current page is a list page for a particular article type.
Note: When registering an article type, the article type with parameter 'has_archive'=> true will have a list page.
Comment pop-up window
Whether or not it is in the "Comment Popup Window".
Any page containing an article
Returns true if comments are allowed on the current post
Returns true if pinging is allowed for the current article
The "Page" page
The term "page" as used in this section refers to the WordPress web page, rather than any of the pages in my site, or in other words, referring to the built-in 'page' article types.
When the current page is a "page".
is_page ('42')
Returns true if the current page is page ID 42.
is_page ('About Me')
Returns true if the title of the current page is "About me".
is_page ('about-me')
Returns true if the alias of the current page is "About me".
is_page (array(42, 'about-me', 'About Me'))
current page's ID is 42, or post_name is "about-me", or post_title Returns true if it is "About Me".
is_page (array(42,54,6))
Returns true if the current page is ID 42, 54, or 6.
Test Page Pagination
We can use this code to check if we are using QuickTag <!--nextpage-->
on the nth page of an article or page that is split into multiple pages. This can sometimes be useful, for example if you want to display metadata only on the first page of an article divided into multiple pages.
Example 1
get( 'page' );
if ( ! $paged || $paged
Example 2
<?php
$paged = get_query_var( 'page' ) ? get_query_var( 'page' ) : false;
if ( $paged == false ) {
// 这不是一个有分页的页面,或是有分页页面中的第一页
} else {
// 这是一个有分页的页面
}
?>
Test subpages
WordPress No is_subpage()
function, but there are other ways to test whether the current page is a child of another page:
Code Snippet 1
post_parent ) {
// This is a child page
} else {
// This is not a child page
}
? >
We can use the Code Snippet 2 Create your own is_subpage() function from the code in the Add it to the functions.php file. It tests for being a subpage in the same way that Snippet 1 does, but returns the ID of the parent page if it is, or false if it isn't.
Code Snippet 2
function is_subpage() {
global $post.
if ( is_page() && $post->post_parent ) {
return $post->post_parent; } else {
} else {
return false; } else { return $post->post_parent; } else {
}
}
If we need to test subpages frequently, it is recommended to use the functions in Snippet 2 instead of copying them each time we need to test them as in Snippet 1.
To test if the parent page of a page is a specific page, such as "About" (page ID 2), we can use the tests in Snippet 3. These tests check to see if we are viewing the specified page or its children. This is important for setting up specific content for different parts of the site, e.g., we can have different titles and banners for different pages, sub-pages.
Code segment 3
post_parent ) {
// The page title is "About", or the parent page of "About".
$bannerimg = 'about.jpg';
} elseif ( is_page( 'learning' ) || '56' == $post->post_parent ) {
$bannerimg = 'teaching.jpg';
} elseif ( is_page( 'admissions' ) || '15' == $post->post_parent ) {
$bannerimg = 'admissions.jpg';
} else {
$bannerimg = 'home.jpg'; // when on other pages
}
? >}
Snippet 4 is a function that allows us to perform the above test more easily. This function will return true if we are looking at a specific page (e.g. "About") or one of its children (the parent ID of this page is "2").
Code Snippet 4
function is_tree( $pid ) {
global $post;
if ( is_page($pid) ){
return true;
}
$anc = get_post_ancestors( $post->ID );
foreach ( $anc as $ancestor ) {
if( is_page() && $ancestor == $pid ) {
return true;
}
}
return false;
}
Add Snippet 4 to the theme's functions.php file and call is_tree('id') to see if the current page is a page, or a child of a page. In Snippet 3, is_tree('2') replaces the first if tag inside the "is_page('about') || '2' == $ post-> post_parent"
Note that if we have more than one page level, the parent page is the direct parent of the current page, not the topmost page in the hierarchy.
Whether it is a page template
WordPress allows us to determine if the current page uses a page template or if a specific page template is used.
Are page templates used?
is_page_template('about.php')
Is the "about.php" page template used? Please note that unlike the other judgment functions, if you want to specify a page template, you need to use a file name such as about.php or my_page_template.php.
Note: If the template file is located in a subdirectory, the directory also needs to be included in the parameter, e.g. 'page-templates/about.php'.
category page
Returns true when the "Category Archive" screen is displayed.
is_category('9')
Returns true if the archive page of the catalog with ID 9 is displayed.
is_category('Stinky Cheeses'))
Returns true when the archive page of a category with the name "Stinky Cheeses" is displayed.
is_category('blue-cheese')
Returns true when displaying the archive page of a category with the alias "blue-cheese".
is_category( array(9, 'blue-cheese', 'Stinky Cheeses') )
Returns true when displaying an archive page of a catalog with ID 9, or with the alias "blue-cheese", or with the name "Stiky Cheeses".
in_category('5')
Returns true if the current article is in a category with ID 5.
in_category(array(1,2,3))))
Returns true if the current article is in a category with ID 1, 2, or 3.
!in_category( array(4,5,6)))
Returns true if the current category is not in a category with an ID of 4, 5, or 6.
Note: When using the functions above, be sure to watch your spelling, there is a big difference between "is" and "in".
See also is_archive() respond in singing Categorized catalog templatesThe
Tagged archive page
Whether it is a tag archive page
is_tag('Article Type')
Whether or not to archive pages for tags named "Post Type".
is_tag(array('sharp', 'mild', 'extreme'))
Returns true if the label alias is "sharp", "mild" or "extreme".
Returns true if the current post has a tag. must be used in a post loop.
has_tag('Article type')
Returns true if the label of the current article is "article type".
has_tag( array('sharp', 'mild', 'extreme')) )
Returns true if the current post has an alias that is any of an array.
See also is_archive() respond in singing Label templatesThe
Taxonomy archive page
Is it a taxonomy archive page
is_tax('flavor')
Returns true if the page is displayed as an archive of a taxonomy called flavor.
is_tax('flavor', 'mild'))
When displaying the archive page of a taxonomy item whose Flavor is mild.
is_tax('flavor', array('sharp', 'mild', 'extreme '))
Returns true if the flavor taxonomy item archive page is displayed with an alias of "sharp", "mild" or "extreme".
Checks if the current article contains the specified taxonomy item. The first argument should be an empty string. Requires the taxonomy item alias/name as the second argument.
has_term('green', 'color'))
Current articles have taxonomy items colored green.
has_term(array('green', 'orange', 'blue'), 'color ')
Current articles have taxonomy items colored green, orange, and blue.
See also is_archive()The
Registration Classification Criteria
When a classification has been adopted register_taxonomy() Returns true when registering. Previously is_taxonomy() Deprecated in version 3.0.
author page
Returns true when the author archive page is displayed.
is_author('4'))
Returns true if the author archive page with ID 4 is displayed.
is_author('Vivian'))
When displaying the archive page of an author with the nickname "Vivian".
is_author ('john-jones')
Returns true if the archive page with the nicename "john-jones" is displayed.
is_author( array(4, 'john-jones', 'Vivian') )
Returns true if the author's archive page with ID 4 or user_nicename "john-jones" or nickname "Vivian" is displayed.
See also is_archive() respond in singing Author TemplatesThe
Multi-Author Sites
When multiple authors publish website articles. Applies to version 3.2.
date page
Returns true when any date archive page is displayed.
Returns true when the yearly archive is displayed.
When to archive monthly, returns true.
Returns true when the daily archive is displayed.
Returns true when hourly, minute or secondly archives are displayed.
Determine if the post date of the current article in the loop is different from the previous one.
Any archive page
Returns true when any type of archive page is displayed (e.g. categorized directories, tags, authors, and date archives).
Search results page
Returns true when the search results page archive is displayed.
404 Page
Returns true in the event of an "HTTP 404: Not Found" error.
Single attachment page
Returns true if the current page is an attachment to an article or page. attachments are images or other files uploaded through the article editor that can be displayed on their own "page" or template.
Single page, single article or attachment
When any of the following functions return true: is_single()
(math.) genus is_page()
maybe is_attachment()
This function returns true.
is_singular('book')
but returns true if the article type is 'book'.
is_singular(array('newspaper', 'book')))
Returns true when displaying a single page with article type 'newspaper' or 'book'.
subscription feed
Returns true if the current page is a subscription source page.This function is not commonly used in theme development, and is generally used within WordPress or during plugin development.
quote
Returns true when the requested page is a WordPress Trackback engine. this function is not commonly used during theme development, and is generally used within WordPress or during plugin development.
previews
Returns true when the preview mode is viewing an article or page.
summarized
Returns true if the current article has a summary.
has_excerpt()
Returns true when the article with ID 42 has a summary.
post_excerpt ) ) {
// This post does not have an excerpt
} else {
// This post should be summarized
}
? >
Other Uses
The following code can be used when we need to hide the automatic summary and show only the manual summary.
}
Replace the text or code with an automatic summary.
<?php
if ( ! has_excerpt() ) {
// 你的文字或代码
}
?>
Whether the navigation menu has been assigned
Whether the registered navigation menu location has been assigned a menu
Returns: allocated (true) or unallocated (false)
in-cycle
Checks if you are "inside the article loop". This function is useful for plugin developers, this condition returns true when we are in a loop.
Whether the sidebar is activated (with widgets)
Checks if the specified sidebar is active (has widgets in it). Returns true if there are widgets in the usage sidebar (identified by name, logo or number), otherwise false.
Whether the current site is part of a network (multisite)
Check if the current site is in a WordPress MultiSite installation.
Primary site (multi-site)
Determine if the site is the primary site in the network.
Network Administrator (multi-site)
Determines if the user is a network (super) administrator.
Whether the plugin is activated or not
Check if the plugin is activated.
subtheme
Checks if the current site is using a child theme.
Does the theme support a feature
Check if the theme supports a certain feature.
code example
Below are various examples of the use of conditional functions, demonstrating how we can use these conditional tags.
Article Details
This example demonstrates how to use the is_single()
Set specific content to be displayed only when viewing a single article page:
if ( is_single() ) {
echo 'This is just one of many fabulous entries in the ' . single_cat_title() . ' category!
}
This is an example of using a conditional function in a loop to display the full content of an article when we are viewing the home page or a single article page, and a summary in other cases.
if ( is_home() || is_single() ) {
the_content(); } else {
} else {
the_excerpt(); } else {
}
The following code can be used when we need to display something on a page other than the home page.
} ?
Checking multiple conditions
We can use the PHP Operators Determine multiple conditions in a single if statement. This processing is useful when we need to check if the current page satisfies multiple conditions.
if ( is_single() || is_page() ) {
// If the current page is a single post page or page detail, show the content here.
}
if ( is_archive() && ! is_category( 'nachos' ) ) {
// Show here if the current page is an archive page, not a 'nachos' category.
}
if ( $query->is_main_query() && is_post_type_archive( 'products' ) && ! is_admin() ) {
// If the current page has a main query and is a 'products' post type archive page and is not in the admin page, show content here not in the WordPress admin, then do something special
}
if ( is_post_type_archive( 'movies' ) || is_tax( 'genre' ) || is_tax( 'actor' ) {
// If it's an archive page for the 'movies' post type
// or an archive page for the taxonomy 'genre'
// or the archive page for taxonomy 'actor'.
}
Difference based on date
If someone browses our site by date, let's use different colors to differentiate between posts from each year:
<?php
if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<h2 id="post-<?php the_ID(); ?>">
<a href="/en/</?php the_permalink() ?>" rel="bookmark">
<?php the_title(); ?>
</a>
</h2>
<small>by</small>
<?php
if ( is_date() ) {
if ( date( 'Y' ) != get_the_date( 'Y' ) ) {
// 这是去年的文章,我们添加一个 “oldentry” 的类
// 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>
Variable sidebar content
The following example displays different sidebars depending on which page the user visits.
<div id="sidebar">
<?php
if ( is_home() ) {
// 我们在首页,显示所有顶级分类的列表
wp_list_categories( 'optionall=0&sort_column=name&list=1&children=0' );
} elseif ( is_category() ) {
// 我们在单页面,显示所有分类列表
wp_list_categories( 'optionall=1&sort_column=name&list=1&children=1&hierarchical=1' )
} elseif ( is_single() ) {
// 我们在单文章页面,不显示任何内容
} elseif ( is_page() ) {
// 我们在页面中,接下来检查在哪一个页面
if ( is_page( 'About' ) ) {
// 关于我们页面
echo "这是关于我们页面!";
} elseif ( is_page( 'contact' ) ) {
echo "这是联系我们页面。";
} else {
echo "其他页面";
}
} else {
echo "其他页面";
}
</div>
Friendly 404 page
Creating a friendly 404 page can make it easier for users to navigate the site, such as prompting users to return to the home page or search when a 404 error occurs.
if ( is_404() ) {
ehco "The current page was not found, please return to the home page or search for what you need." ;
}
In the theme's footer.php file
Sometimes queries executed in other templates (such as sidebar.php) may break certain conditional tags. For example, the conditional tags work fine in header.php, but not in the theme's footer.php. The trick to fixing this is to place wp_reset_query before the conditional test in the footer. e.g.:
}
Conditional Labeling Function Index
- comments_open
- has_tag
- has_term
- in_category
- is_404
- is_admin
- is_archive
- is_attachment
- is_author
- is_category
- is_child_theme
- is_comments_popup
- is_date
- is_day
- is_feed
- is_front_page
- is_home
- is_month
- is_multi_author
- is_multisite
- is_main_site
- is_page
- is_page_template
- is_paged
- is_preview
- is_rtl
- is_search
- is_single
- is_singular
- is_sticky
- is_super_admin
- is_tag
- is_tax
- is_time
- is_trackback
- is_year
- pings_open
function reference
- Function. comments_open()
Function. is_404()
Function. is_admin()
Function. is_admin_bar_showing()
Function. is_archive()
Function. is_attachment()
Function. is_author()
Function. is_category()
Function. is_comments_popup()
Function. is_date()
Function. is_day()
Function. is_feed()
Function. is_front_page()
Function. is_home()
Function. is_local_attachment()
Function. is_main_query
Function. is_multi_author
Function. is_month()
Function. is_new_day()
Function. is_page()
Function. is_page_template()
Function. is_paged()
Function. is_plugin_active()
Function. is_plugin_active_for_network()
Function. is_plugin_inactive()
Function. is_plugin_page()
Function. is_post_type_archive()
Function. is_preview()
Function. is_search()
Function. is_single()
Function. is_singular()
Function. is_sticky()
Function. is_tag()
Function. is_tax()
Function. is_taxonomy_hierarchical()
Function. is_time()
Function. is_trackback()
Function. is_year()
Function. in_category()
Function. in_the_loop()
Function. is_active_sidebar()
Function. is_active_widget()
Function. is_blog_installed()
Function. is_rtl()
Function. is_dynamic_sidebar()
Function. is_user_logged_in()
Function. has_excerpt()
Function. has_post_thumbnail()
Function. has_tag()
Function. pings_open()
Function. email exists()
Function. post_type_exists()
Function. taxonomy_exists()
Function. term_exists()
Function. username exists()
Function. wp_attachment_is_image()
Function. wp_script_is()