Introduction to WordPress conditional tags

WordPress comes with something called conditional tags, which let’s you change how content is displayed depending on what conditions that are met. For example, you can check if the user is on the frontpage, or if she is logged in or not.

in this article we’ll go through how to use these conditional tags, and how they work. If you are familiar to PHP, this will be a walk in the park. Otherwise, dont worry, I’ll show you how it works.

PHP if(statements)

With PHP if statements you can ask if something is true or false, 1 or 0. If your statement is true, your code will be executed, and if it’s false nothing will happen. Check out the example, and I’m sure you’ll understand.

&lt;?php<br />
if(10 == 10):<br />
    echo 'This is true, and will be shown.';<br />
<p>if(10 == 15):<br />
    echo 'This is false, and will not be shown.';<br />
endif;<br />

You can also use elseif which let’s you add another statement, and else that will be executed if you’re first statement is false.

&lt;?php<br />
if(10 == 11):<br />
    echo 'This is false, and will not be shown.';<br />
elseif(10 == 15):<br />
    echo 'This is false, and will not be shown.';<br />
else:<br />
    echo 'Since none of the above is true, this will be shown.';<br />
endif;<br />

That’s all you neet to know about PHP if statements for now, let’s get on with WordPress conditional tags! However, if you want to digg deeper into PHP if statements, head over to

How conditional tags work

When using the native WordPress function like is_home(), you simply ask WordPress if the user is currently on the homepage or not. WordPress will then answer with 0 for no, and 1 for yes.

&lt;?php<br />
if( is_home() ):<br />
    echo 'User is on the homepage.';<br />
else:<br />
    echo 'User is not on the homepage';<br />
endif;<br />

For a complete list over WordPress conditional tags you can visit their codex.

Combining statements

There are cases when you might want to check more than one statement. This is easily done by using AND and OR.

&lt;?php<br />
if( is_home() AND is_page( 5 ) ):<br />
    echo 'User is on the homepage, and the home pages ID is 5';<br />
endif;   </p>
<p>if( is_home() OR is_page( 5 )):<br />
    echo 'User is on the homepage or the page where the ID is 5';<br />
endif;<br />

When to use conditional tags

Conditional tags are great when you want to change your content depending on the answers of question relevant to your site. Is the user logged in? Is she using Internet Explorer? Is there any post to be shown?

To get an example of conditional tags in use, we don’t have to look further than to Twenty Eleven’s(the standard theme in WP 3.2) index.php, line 20.

&lt;?php if ( have_posts() ) : ?><br />
... posts ...<br />
&lt;?php else : ?><br />
... search field ...<br />
&lt;?php endif; ?><br />

This checks if there is any posts to show, and if not, the search field is displayed.

Examples of WordPress conditional tags

if( is_admin() ):<br />
    # User is administator<br />
if( is_home() AND is_page('1') ):<br />
    # The user is at the home page and the home page is a page with the ID 1<br />
if( is_single() OR is_page() ):<br />
    # The user is reading a post or a page<br />
if( !is_home() AND is_page() ):<br />
    # The user is on a page, but not the homepage<br />

Custom conditional tags

The conditional tags available in their codex page are pretty limited to the big parts of WordPress, like posts, pages and such. There are, however, alot of small statements available if you look around.

Check if user is logged in

If you have a blog with users, this is a handy snippet. It simply checks whether the user is logged in or not.

if ( is_user_logged_in() ):<br />
    echo 'Welcome, registered user!';<br />
else:<br />
    echo 'Welcome, visitor!';<br />
endif;<br />

Show content if registration open / closed

This is great if you have users on your blog and want to let members in only when there’s room for it. This conditional tag let’s you display content depending on if registrations are open or closed.

&lt;?php if ( get_option('users_can_register'):<br />
     echo 'Registrations are open.';<br />
else:<br />
    echo 'Registrations are closed.';<br />

Check if user is on a Mac or a PC

If you’re developing software for multiple operating systems and want to know which one the user is on, this is what you’re looking for.

if( stristr($_SERVER['HTTP_USER_AGENT'],"mac") ):<br />
  echo 'Hello, I'm a Mac.';<br />
else:<br />
  echo 'And I'm a PC.';<br />

Disable Google Analytics for logged in users

In case you’re using Google Analytics for website analytics, you probably only want to track real visitors, and not authors and writers. Dont forget to change UA-XXXXXXX-X to your Google Analytics ID.

&lt;?php<br />
// function for inserting Google Analytics into the wp_head<br />
add_action('wp_footer', 'ga');<br />
function ga() {<br />
   if ( !is_user_logged_in() ): // íf user is not logged in<br />
?><br />
	&lt;script type="text/javascript"><br />
	  var _gaq = _gaq || [];<br />
	  _gaq.push(['_setAccount', 'UA-XXXXXXX-X']); // insert your Google Analytics id here<br />
	  _gaq.push(['_trackPageview']);<br />
	  _gaq.push(['_trackPageLoadTime']);<br />
	  (function() {<br />
	    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;<br />
	    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '';<br />
	    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);<br />
	  })();<br />
	&lt;/script><br />
&lt;?php<br />
   endif;<br />
}<br />

Check if post is custom post type

With this conditional tag you can check if the current post is in a specific custom post type, in this example books.

&lt;?php if ( is_singular( 'books' ) ):<br />
    // This post is of the custom post type books.<br />
endif; ?>

Redirect to post if search query only returns single result

Adding this snippet to the functions.php of your wordpress theme will redirect your search to the post automatically when wordpress only returns a single search result.

&lt;?php<br />
add_action('template_redirect', 'single_result');<br />
function single_result() {<br />
    if (is_search()) {<br />
        global $wp_query;<br />
        if ($wp_query->post_count == 1) {<br />
            wp_redirect( get_permalink( $wp_query->posts['0']->ID ) );<br />
        }<br />
    }<br />
}<br />

Check if last post

If you, for example, are using separators between your posts you probably don’t want one on the last post of the page. Add the following conditional tag inside your loop where you want to display something only if it’s on not the last post.

&lt;?php if( ($wp_query->current_post + 1) < ($wp_query->post_count) ): ?><br />
    &lt;div class="separator">&lt;/div><br />
&lt;?php endif; ?>

Check if current user can…

Sometimes you might want to know what role a user have, for example if you only want certain links(like edit etc) to be displayed for authors and not for visitors.

The function current_user_can() does just that. See the examples below:

&lt;?php<br />
if( current_user_can('editor') ):<br />
    // true if user is an editor<br />
endif;<br />
if( !current_user_can('administrator') ):<br />
    // true if user is not admin<br />
endif;<br />
if( current_user_can('edit_posts') ):<br />
    // true if user can edit posts<br />
endif;<br />

Disable Tinymce HTML editor for everyone but admin

Adding this snippet to the functions.php of your wordpress theme will disable the Tinymce HTML editor for everyone but the admin.

&lt;?php<br />
add_filter( 'wp_default_editor', create_function('', 'return "tinymce";') );<br />
add_action( 'admin_head', 'disable_html_editor_wps' );<br />
function disable_html_editor_wps() {<br />
	global $current_user;<br />
	get_currentuserinfo();<br />
	if ($current_user->user_level != 10) {<br />
		echo '&lt;style type="text/css">#editor-toolbar #edButtonHTML, #quicktags {display: none;}&lt;/style>';<br />
	}<br />
}<br />
?><br />

Check if user is coming from StumbleUpon

StumbleUpon is a great way to drive traffic to your website. To get the attention of Stumblers can be though, so the bounce rate is often high on their visits.

To higher the chance of getting them to stay at your website, you can display a special message to them. This conditional tag checks if the user comes from StumbleUpon and let’s you do something if they are.

&lt;?php if( strpos($_SERVER[HTTP_REFERER], "" ) == true ): ?><br />
    &lt;div class="welcome-stumbleupon"><br />
        &lt;p>Hello StumbleUpon user!&lt;/p><br />
    &lt;/div><br />
&lt;?php endif; ?>

A last word

Hopefully you found WordPress conditional tags to be as awesome as I do. It saves me tons of time while developing templates, not having to come up with my own statements. Make sure take a look at the codex to see what else can be done with it. Happy coding!