• Posted: 2012-01-10
  • Author: Filip Stefansson
  • Tags: Tutorials

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.

<?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 let’s you add another statement, and else that will be executed if you’re 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 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 php.net.

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.

<?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 don’t have to look further than to 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 posts to show, and if not, the search field is displayed.

Examples 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;

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() ):
    echo 'Welcome, registered user!';
else:
    echo 'Welcome, visitor!';
endif;

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.

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

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") ):
  echo 'Hello, I'm a Mac.';
else:
  echo 'And I'm a PC.';
endif;

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.

<?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;
}
?>

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.

<?php if ( is_singular( 'books' ) ):
    // This post is of the custom post type books.
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.

<?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 ) );
        }
    }
}
?>

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.

<?php if( ($wp_query->current_post + 1) < ($wp_query->post_count) ): ?>
    <div class="separator"></div>
<?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:

<?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;
?>

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.

<?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>';
	}
}
?>

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.

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

Share this snippet

If you like this snippet, share it with friends!