WordPress Conditional Tags (And Snippets) for Beginners

By Filip Stefansson. Filed in Wordpress

One of the best features of the WordPress could be the conditional tags. It allows you to tell the code to act differently in specific situations. For example, you can check if the user is using Windows or Mac, and display different content based on the systems. You can also redirect to post if search query only returns single result. You name the situations, the conditional tags can recognize them all!

wordpress conditional tags

Despite its flexibility on determining actions based on different situations, it’s also extremely easy to learn, and there are even tutorials and resources spread over the web for you to actually master it. That said, in this article we’ll go through a detailed introduction about the conditional tags, how they work and when to actually use them.

In the last section of the article we’ll also show 10 useful snippets for you to achieve the most with conditional tags, so get them all to make your WordPress site acts more intelligently to unique situations!

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, depending on how you decide the actions in the conditional tags. Check out the example, and I’m sure you’ll understand what I’m talking about.

<?php
if(10 == 10):  
    echo 'This is true, and will be shown.';
endif;

if(10 == 15):  
    echo 'This is false, and will not be shown.';
endif;
?>

You can also use elseif which lets you add another statement, and else that will be executed if your first statement is false.

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

That’s all you need to know about if statements for now, let’s get into WordPress conditional tags! However, if you want to dig deeper into PHP if statements, head over to php.net for reference.

How Conditional Tags Work?

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

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

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.

<?php 
if( is_home() AND is_page( 5 ) ):
    echo 'User is on the homepage, and the home pages ID is 5';
endif;   

if( is_home() OR is_page( 5 )):
    echo 'User is on the homepage or the page where the ID is 5';
endif;
?>

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 can look into Twenty Eleven’s (the standard theme in WP 3.2) index.php, line 20.

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

This checks if there is any post to show, and if the answer is no, the search field is displayed.

Below is another example of WordPress conditional tags:

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

10 Useful Conditional Tags

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

Check if user is logged in

This will be a handy snippet if you have a blog with users registered, as it checks whether your user is logged in or not.

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

[Source]

Show content if registration are opened / closed

A good snippet if you have user registration feature in your site, and you want to let visitors to know about whether the registrations are opened or closed.

<?php if ( get_option('users_can_register'):
     echo 'Registrations are opened.'; 
else:
    echo 'Registrations are closed.'; 
endif;

[Source]

Check if user is on a Mac or a PC

Want to provide specific content based on the Operating System that users are using? Here’s the snippet for you.

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

[Source]

Disable Google Analytics for logged in users

If you are using Google Analytics and you only want to track the visitors other than your authors and writers, you can probably use this snippet to achieve the purpose. Be sure to change UA-XXXXXXX-X to your Google Analytics ID.

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

[Source]

Check if post is custom post type

Using the conditional tag below you can check if the current post is in a specific custom post type, for example, books.

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

[Source]

Redirect to post if search query only returns single result

Add this snippet to your WordPress theme‘s functions.php to redirect your search to post automatically when WordPress only returns a single search result.

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

[Source]

Check if last post

The chances are if you’re using separators between your posts you probably don’t want to include it into the last post of the page. Include the conditional tag below into your loop where you want to display something only if it’s on the last post.

<?php if( ($wp_query->current_post + 1) < ($wp_query->post_count) ) { ?>
    <div class="separator"></div>
<?php } ?> 

[Source]

Check if current user can…

There are times when you want to know the role of the users, for example you only want certain links (edit, etc) to be displayed for authors. The function current_user_can() works like what mentioned above, and here is the code:

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

[Source]

Disable Tinymce HTML editor for everyone but admin

Ever wanted to disable the Tinymce HTML editor for everyone but admin? Here’s the snippet for you.

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

[Source]

Check if user is coming from StumbleUpon

StumbleUpon is a great social media which is able to attract traffic to your site. Here’s a trick to attract the Stumblers: display a special message to welcome them by using the conditional tag below which checks if the user comes from StumbleUpon.

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

[Source]

Final words

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.

Also make sure to take a look at the WordPress Codex to see what else can be done with it. Happy coding!

More:

Looking forward to make your WordPress site even better? Here are the resources for you!

Editor’s note: This post is written by Filip Stefansson for Hongkiat.com. Filip is a web developer & WordPress enthusiast from Sweden. He is also the founder and editor over at WP-Snippets, and co-founder of Pixby Media AB.

Advertisement