WordPress Conditional Tags

Conditional tags are functions which return true or false. They tell your code what kind of page is being shown, so you can change the output for the home page, a post, a page, a category or a search.

Common conditional tags

TagTrue when
is_front_page()The front page of the site is shown (the blog list or the static page)
is_home()The blog posts index is shown
is_single()One post (or any custom post type item, not a page) is shown
is_page()One page is shown. Can take an ID, title or slug: is_page( 'about' )
is_singular()Any single item: post, page or custom post type
is_category(), is_tag(), is_tax()An archive of that taxonomy
is_archive()Any archive (category, tag, author, date)
is_search()The search results page
is_404()A not found page
is_user_logged_in()The visitor is logged in
is_admin()The dashboard is being shown

See them in action

This footer prints which tags are true on each page. First we make the theme:

<footer>
<?php
$checks = array( 'is_front_page', 'is_home', 'is_single', 'is_page', 'is_category', 'is_search', 'is_404' );
$true   = array();
foreach ( $checks as $fn ) {
	if ( $fn() ) {
		$true[] = $fn . '()';
	}
}
echo 'TRUE: ' . implode( ', ', $true );
?>
</footer>
<?php wp_footer(); ?>
</body>
</html>
Terminal output

$ for u in / /hello-world/ /sample-page/ /category/uncategorized/ "/?s=hello" /no-such-page/; do echo "$u => $(curl -s http://example.com$u | grep -o 'TRUE: [^<]*')"; done
/ => TRUE: is_front_page(), is_home()
/hello-world/ => TRUE: is_single()
/sample-page/ => TRUE: is_page()
/category/uncategorized/ => TRUE: is_category()
/?s=hello => TRUE: is_search()
/no-such-page/ => TRUE: is_404()

On the home page both is_front_page() and is_home() are true, because the site shows the latest posts. If you set a static front page in Settings > Reading, they become different: the static page is the front page, and the blog page is home.

Use them in a template

<?php if ( is_front_page() ) : ?>
	<section class="hero">Welcome to our site!</section>
<?php elseif ( is_category( 'news' ) ) : ?>
	<p>You are reading the news archive.</p>
<?php endif; ?>

<?php if ( is_user_logged_in() ) : ?>
	<a href="<?php echo esc_url( wp_logout_url() ); ?>">Log out</a>
<?php endif; ?>

Use them in the right place

Conditional tags only work after WordPress has read the URL, which means after the wp action. Using them too early, for example directly in functions.php (outside a hook), gives wrong results and a notice. Put them inside a function which runs on a hook like wp_enqueue_scripts.

Note: Many tags accept arguments for specific items: is_page( array( 'about', 'contact' ) ), is_single( 42 ), is_category( 'news' ). Next: Register Sidebar.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.