Codex

Interested in functions, hooks, classes, or methods? Check out the new WordPress Code Reference!

Conditional Tags

Contents

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 is_home() Conditional Tag, that task is made easy.

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

Warning: You can only use conditional query tags after the posts_selection action hook in WordPress (the wp action hook is the first one through which you can use these conditionals). For themes, this means the conditional tag will never work properly if you are using it in the body of functions.php, i.e. outside of a function.

However: if you have a reference to the query object (for example, from within the parse_query or pre_get_posts hooks), you can use the WP_Query conditional methods (eg: $query->is_search())

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. This is the page which shows the time based blog content of your site, so if you've set a static Page for the Front Page (see below), then this will only be true on the Page which you set as the "Posts page" in Administration > Settings > Reading.

The Front Page

is_front_page() 
When the front of the site is 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.

The Blog Page

is_front_page() and is_home() 

There is no conditional tag for the blog page. You have to use both is_home() and is_front_page() to detect this page, but those functions can be misused. In fact, a user can define a static page for the homepage, and another page to display the blog. This one will return true with is_home() function, even if it's not the homepage. Here is what a user can define :

  • a default homepage (with the latest posts)
  • a static homepage and no blog page
  • a static homepage and a blog page

When you use is_home() and is_front_page(), you have to use them in the right order to avoid bugs and to test every user configuration:

if ( is_front_page() && is_home() ) {
  // Default homepage
} elseif ( is_front_page() ) {
  // static homepage
} elseif ( is_home() ) {
  // blog page
} else {
  //everything else
}

The Administration Panels

is_admin()
When the Dashboard or the administration panels are being displayed.
is_network_admin()
When the Network Dashboard or the Network administration panels for multisite are being displayed.

Attention: The wp-login.php page is not an admin page. To check if this page is displayed, use the admin global variable $pagenow.

The Admin Bar

is_admin_bar_showing() 
Returns true if the admin bar will be displayed.

Note : To display or not this bar, use show_admin_bar(), this function should be called immediately upon plugins_loaded or placed in the theme's functions.php file.

A Single Post Page

is_single() 
When a single post of any post type (except attachment and page post types) is being displayed.
is_single( '17' ) 
When Post 17 is being displayed as a single Post.
is_single( 'Irish Stew' ) 
When the Post with Title "Irish Stew" is being displayed as a single Post.
is_single( 'beef-stew' ) 
When the Post with Post Slug "beef-stew" is being displayed as a single Post.
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".
is_single( array( 17, 19, 1, 11 ) ) 
Returns true when the single post being displayed is either post ID = 17, post ID = 19, post ID = 1 or post ID = 11.
is_single( array( 'beef-stew', 'pea-soup', 'chili' ) ) 
Returns true when the single post being displayed is either the post_name "beef-stew", post_name "pea-soup" or post_name "chili".
is_single( array( 'Beef Stew', 'Pea Soup', 'Chili' ) ) 
Returns true when the single post being displayed is either the post_title is "Beef Stew", post_title is "Pea Soup" or post_title is "Chili".

Note: This function does not distinguish between the post ID, post title, or post name. A post named "17" would be displayed if a post ID of 17 was requested. Presumably the same holds for a post with the slug "17".

A Sticky Post

is_sticky() 
Returns true if "Stick this post to the front page" check box has been checked for the current post. In this example, no post ID argument is given, so the post ID for the Loop post is used.
is_sticky( '17' ) 
Returns true when Post 17 is considered a sticky post.

A Post Type is Hierarchical

is_post_type_hierarchical( $post_type ) 
Returns true if this $post_type has been set with hierarchical support when registered.
is_post_type_hierarchical( 'book' ) 
Returns true if the book post type was registered as having support for hierarchical.

A Post Type Archive

is_post_type_archive() 
Returns true on any post type archive.
is_post_type_archive( $post_type ) 
Returns true if on a post type archive page that matches $post_type.
is_post_type_archive( array( 'foo', 'bar', 'baz' ) ) 
Returns true if on a post type archive page that matches either "foo", "bar", or "baz".

To turn on post type archives, use 'has_archive' => true, when registering the post type.

A Comments Popup

is_comments_popup() 
When in Comments Popup window.

Any Page Containing Posts

comments_open()
When comments are allowed for the current Post being processed in the WordPress Loop.
pings_open()
When pings are allowed for the current Post being processed in the WordPress Loop.

A PAGE Page

This section refers to WordPress Pages, not any generic web page from your blog, or in other words to the built in post_type 'page'.

is_page() 
When any Page is being displayed.
is_page( 42 ) 
When Page 42 (ID) is being displayed.
is_page( 'About Me And Joe' ) 
When the Page with a post_title of "About Me And Joe" is being displayed.
is_page( 'about-me' ) 
When the Page with a post_name (slug) of "about-me" is being displayed.
is_page( array( 42, 'about-me', 'About Me And Joe' ) ) 
Returns true when the Pages displayed is either post ID = 42, or post_name is "about-me", or post_title is "About Me And Joe".
is_page( array( 42, 54, 6 ) ) 
Returns true when the Pages displayed is either post ID = 42, or post ID = 54, or post ID = 6.

See also is_page() for more snippets, such as is_subpage, is_tree.

Note: There is no function to check if a page is a sub-page. We can get around the problem:

if ( is_page() && $post->post_parent > 0 ) { 
    echo "This is a child page";
}

Is a Page Template

Allows you to determine whether or not you are in a page template or if a specific page template is being used.

is_page_template() 
Is a Page Template being used?
is_page_template( 'about.php' ) 
Is Page Template 'about' being used?

Note: if the file is in a subdirectory you must include this as well. Meaning that this should be the filepath in relation to your theme as well as the filename, for example page-templates/about.php.

A Category Page

is_category( $category ) 
When the actual page is associated with the $category Category.
is_category( '9' ) 
When the archive page for Category 9 is being displayed.
is_category( 'Stinky Cheeses' ) 
When the archive page for the Category with Name "Stinky Cheeses" is being displayed.
is_category( 'blue-cheese' ) 
When the archive page for the Category with Category Slug "blue-cheese" is being displayed.
is_category( array( 9, 'blue-cheese', 'Stinky Cheeses' ) ) 
Returns true when the category of posts being displayed is either term_ID 9, or slug "blue-cheese", or name "Stinky Cheeses".
is_category( 5 ) || cat_is_ancestor_of( 5, get_query_var( 'cat' ) ) 
Returns true when the category of posts being displayed is either term_id 5, or an ancestor of term_id 5 (subcategory, sub-subcategory...).
in_category( '5' ) 
Returns true if the current post is in the specified category id (read more).
in_category( array( 1,2,3 ) ) 
Returns true if the current post is in either category 1, 2, or 3.
! in_category( array( 4,5,6 ) ) 
Returns true if the current post is NOT in either category 4, 5, or 6. Note the ! at the beginning.

Note: Be sure to check your spelling when testing: "is" and "in" are significantly different.

See also is_archive() and Category Templates.

A Tag Page

is_tag() 
When any Tag archive page is being displayed.
is_tag( 'mild' ) 
When the archive page for tag with the slug of 'mild' is being displayed.
is_tag( array( 'sharp', 'mild', 'extreme' ) ) 
Returns true when the tag archive being displayed has a slug of either "sharp", "mild", or "extreme".
has_tag() 
When the current post has a tag. Prior to 2.7, must be used inside The Loop.
has_tag( 'mild' ) 
When the current post has the tag 'mild'.
has_tag( array( 'sharp', 'mild', 'extreme' ) ) 
When the current post has any of the tags in the array.

See also is_archive() and Tag Templates.

A Taxonomy Page (and related)

is_tax

is_tax() 
True for custom taxonomy archive pages, false for built-in taxonomies (category and tag archives).
is_tax( 'flavor' ) 
When a Taxonomy archive page for the flavor taxonomy is being displayed.
is_tax( 'flavor', 'mild') 
When the archive page for the flavor taxonomy with the slug of 'mild' is being displayed.
is_tax( 'flavor', array( 'sharp', 'mild', 'extreme' ) ) 
Returns true when the flavor taxonomy archive being displayed has a slug of either "sharp", "mild", or "extreme".

has_term

has_term() 
Check if the current post has any of given terms. The first parameter should be an empty string. It expects a taxonomy slug/name as a second parameter.
has_term( 'green', 'color' ) 
When the current post has the term 'green' from taxonomy 'color'.
has_term( array( 'green', 'orange', 'blue' ), 'color' ) 
When the current post has any of the terms in the array.

term_exists

term_exists( $term, $taxonomy, $parent ) 
Returns true if $term exists in any taxonomy. If $taxonomy is given, the term must exist in this one. The 3rd parameter $parent is also optional, if given, the term have to be a child of this parent, the taxonomy must be hierarchical.

is_taxonomy_hierarchical

is_taxonomy_hierarchical( $taxonomy ) 
Returns true if the taxonomy $taxonomy is hierarchical. To declare a taxonomy hierarchical, use 'hierarchical' => true when using register_taxonomy().

taxonomy_exists

taxonomy_exists( $taxonomy ) 
Returns true if $taxonomy has been registered on this site using register_taxonomy().

See also is_archive().

An Author Page

is_author() 
When any Author page is being displayed.
is_author( '4' ) 
When the archive page for Author number (ID) 4 is being displayed.
is_author( 'Vivian' ) 
When the archive page for the Author with Nickname "Vivian" is being displayed.
is_author( 'john-jones' ) 
When the archive page for the Author with Nicename "john-jones" is being displayed.
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".

See also is_archive() and Author Templates.

A Multi-author Site

is_multi_author( ) 
When more than one author has published posts for a site. Available with Version 3.2.

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_year() 
When a yearly archive is being displayed.
is_month() 
When a monthly archive is being displayed.
is_day() 
When a daily archive is being displayed.
is_time() 
When an hourly, "minutely", or "secondly" archive is being displayed.
is_new_day() 
If today is a new day according to post date. Should be used inside the loop.

See also is_archive().

Any Archive Page

is_archive() 
When any type of Archive page is being displayed. Category, Tag, other Taxonomy Term, custom post type archive, Author and Date-based pages are all types of Archives.

A Search Result Page

is_search() 
When a search result page archive is being displayed.

A 404 Not Found Page

is_404() 
When a page displays after an "HTTP 404: Not Found" error occurs.

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 and will return true on 2nd and subsequent pages of posts. This does not refer to a Post or Page whose content has been divided into pages using the <!--nextpage--> QuickTag. To check if a Post or Page has been divided into pages using the <!--nextpage--> QuickTag, see A_Paged_Page section.

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.

See also Using Image and File Attachments.

Attachment Is Image

wp_attachment_is_image( $post_id ) 
Returns true if the attached file to the post with ID equal to $post_id is an image. Mime formats and extensions allowed are: .jpg, .jpeg, .gif, et .png.

A Local Attachment

is_local_attachment( $url ) 
Returns true if the link passed in $url is a real attachment file from this site.

A Single Page, a Single Post, an Attachment or Any Other Custom Post Type

is_singular() 
Returns true for any is_single(), is_page(), or is_attachment().
is_singular( 'foo' ) 
Returns true if the post_type is "foo".
is_singular( array( 'foo', 'bar', 'baz' ) ) 
Returns true if the post_type is "foo", "bar", or "baz".

See also the Custom Post Types book.

Post Type Exists

post_type_exists( $post_type ) 
Returns true is the given $post_type has been registered on this site using register_post_type().

Is Main Query

is_main_query()
Returns true when the current query (such as within the loop) is the "main" query.

Example with the filter hook the_content

add_action( 'the_content', 'baw_add_social_buttons' );
function baw_add_social_buttons( $content ) {
    if ( ! is_admin() && is_main_query() ) {
        return $content . function_from_a_social_plugin();
    }
    return $content;
}

If, when WordPress tries to display the content of each post in the Loop or in a single post page, we are in the main query, and not admin side, we add some social buttons (for example).

Example with the action hook pre_get_posts

add_action( 'pre_get_posts', 'baw_modify_query_exclude_category' );
function baw_modify_query_exclude_category( $query ) {
    if ( ! is_admin() && $query->is_main_query() && ! $query->get( 'cat' ) ) {
        $query->set( 'cat', '-5' );
    }
}

With pre_get_posts, this is not possible to call directly is_main_query, we should use $query given as a parameter.

A New Day

is_new_day() 
Returns true if today is a new day.

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.

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.

A Preview

is_preview() 
When a single post being displayed is viewed in Draft mode.

Has An Excerpt

has_excerpt() 
When the current post has an excerpt
has_excerpt( 42 ) 
When the post 42 (ID) has an excerpt.

Has A Nav Menu Assigned

has_nav_menu() 
Returns true when a registered nav menu location has a menu assigned.

See also register_nav_menu().

Inside The Loop

in_the_loop() 
Check to see if you are "inside the loop". Useful for plugin authors, this conditional returns as true when you are inside the loop.

Is Dynamic SideBar

is_dynamic_sidebar() 
Returns true if the theme supports dynamic sidebars.

Is Sidebar Active

is_active_sidebar() 
Check to see if a given sidebar is active (in use). Returns true if the sidebar (identified by name or id) is in use.

Note: To display a sidebar's content, use dynamic_sidebar( $sidebar ).

Is Widget Active

is_active_widget( $widget_callback, $widget_id ) 
Returns true if the widget with callback $widget_callback or it's ID is $widget_idwill be displayed on front-end.

Note : To be effective this function has to run after widgets have initialized, at action 'init' or later, see Action Reference.

Is Blog Installed

is_blog_installed() 
Returns true if the current is properly installed.

Note: The cache will be checked first. If you have a cache plugin, which saves the cache values, then this will work. If you use the default WordPress cache, and the database goes away, then you might have problems.

Right To Left Reading

is_rtl() 
Returns true if the current locale est read from right to left (RTL).

Example

 if ( is_rtl() ) {
   wp_enqueue_style(  'style-rtl',  plugins_url( '/css/style-rtl.css', __FILE__ ) );
   wp_enqueue_script( 'script-rtl', plugins_url( '/js/script-rtl.js',  __FILE__ ) );
 }

Part of a Network (Multisite)

is_multisite() 
Check to see whether the current site is in a WordPress MultiSite install.

Main Site (Multisite)

is_main_site() 
Determine if a site is the main site in a network.

Admin of a Network (Multisite)

is_super_admin() 
Determine if user is a network (super) admin.

Is User Logged in

is_user_logged_in() 
Returns true if any user is currently logged-in, any roles.

Email Exists

email_exists( $email ) 
Check whether or not the given email address $email has already been registered to a username, and returns that user's ID or false if does not exists.

Username Exists

username_exists( $username ) 
Check whether or not the given username $username has already been registered to a username, and returns that user's ID or false if does not exists.

An Active Plugin

is_plugin_active( $path ) 
Checks if a plugin is activated.
is_plugin_active( 'akismet/akismet.php' ) 
Checks if Akismet is activated.
is_plugin_inactive( $path ) 
Checks if a plugin is deactivated. Same as ! is_plugin_active( $path ).
is_plugin_active_for_network( $path ) 
Same thing for a network activation on a multisite installation.
is_plugin_page() 
Returns true if the loaded page, admin side is a plugin's one. This function is deprecated depuis since WordPress 3.1, with no known alternative.

A Child Theme

is_child_theme() 
Check whether a child theme is in use.

Theme supports a feature

current_theme_supports() 
Check if various theme features exist.
current_theme_support( 'post-thumbnails' ) 
Returns true if the current theme supports featured images. To add a theme support functionality, use add_theme_support().

Has Post Thumbnail

has_post_thumbnail( $post_id ) 
Returns true if the post with ID equal to $post_id contains a featured image. Theme should support Featured Images, see above.

Script Is In use

wp_script_is( $handle, $list ) 
Returns true if the script with handle is $handle has been 'registered', 'enqueue/queue', 'done', ou 'to_do' depending on $list.

Example

    $handle = 'fluidVids.js';
    $list = 'enqueued';
      if ( wp_script_is( $handle, $list ) ) {
        return;
      } else {
        wp_register_script( 'fluidVids.js', plugin_dir_url(__FILE__).'js/fluidvids.min.js');
        wp_enqueue_script( 'fluidVids.js' );
      }

This would check if the script named 'fluidVids.js' is enqueued. If it is not enqueued, the files are then registered and enqueued.

Is Previewed in the Customizer

is_customize_preview() 
Returns true if the site is being previewed in the Customizer, false otherwise.

Working Examples

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

Single Post

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

if ( is_single() ) {

   echo 'This post\'s title is ' . get_the_title();

}

Add this custom function to your child themes functions.php file and modify the conditional tag to suit your needs.

add_action( 'loop_start', 'add_to_single_posts' );
function add_to_single_posts() {
if ( is_single('post') ) {
echo'<div class="your-class">Your Text or HTML</div>';
    }
}

You could also use:

add_action( 'loop_start', 'wpsites_add_to_single_posts' );
function wpsites_add_to_single_posts() {
if ( is_single() ) {
echo'<div class="your-class">Your Text or HTML</div>';
    }
}

Another example of how to use Conditional Tags in the Loop. Choose to display content or excerpt in index.php when this is a display single post or the home page.

if ( is_home() || is_single() ) {

   the_content();

}
else {

   the_excerpt();

}

When you need display a code or element, in a place that is NOT the home page.

<?php if ( ! is_home() ) {?>

 Insert your markup ...

<?php } ?>

Check for Multiple Conditionals

You can use PHP operators to evaluate multiple conditionals in a single if statement.

This is handy if you need to check whether combinations of conditionals evaluate to true or false.

// Check to see if 2 conditionals are met


if ( is_single() || is_page() ) ) {
  
	// If it's a single post or a single page, do something special

}

if ( is_archive() && ! is_category( 'nachos' ) ) {
  
	// If it's an archive page for any category EXCEPT nachos, do something special

}
// Check to see if 3 conditionals are met


if ( $query->is_main_query() && is_post_type_archive( 'products' ) && ! is_admin() ) {
  
	// If it's the main query on a custom post type archive for Products
	// And if we're not in the WordPress admin, then do something special

}

if ( is_post_type_archive( 'movies' ) || is_tax( 'genre' ) || is_tax( 'actor' )  ) {
  
	// If it's a custom post type archive for Movies
	// Or it's a taxonomy archive for Genre
	// Or it's a taxonomy archive for Actor, do something special

}

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_attribute(); ?>">
<?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>

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_categories( '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_categories( '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( 'name' ) . "</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>That's all.</p>";
} // That's all, folks!
?>
<form id="searchform" method="get" action="<?php echo esc_url( $_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 -->

Helpful 404 Page

The Creating an Error 404 Page article has an example of using the PHP conditional function isset() in the Writing Friendly Messages section.

Dynamic Menu Highlighting

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

In a theme's footer.php file

At times queries performed in other templates such as sidebar.php may corrupt certain conditional tags. For instance, in header.php a conditional tag works properly but doesn't work in a theme's footer.php. The trick is to put wp_reset_query before the conditional test in the footer. For example:

<?php
wp_reset_query();
if ( is_page( '2' ) ) {
    echo 'This is page 2!';
} 
?>

Conditional Tags Index

Alphabetical List

Function Reference

See also index of Function Reference and index of Template Tags.

External Resources