Using Conditional Tags to Supercharge Your Blog

Using Conditional Tags to Supercharge Your Blog

Tutorial Details
  • Program: WordPress
  • Version: 3.0+
  • Difficulty: Varies from "easy" to "medium"
  • Estimated Completion Time: 5 minutes for each function

Conditional Tags are one of the many great structures that WordPress has to help us develop for WordPress easier. In this article, we’re going to get to know some of them and use them in example functions like removing things from the error pages or changing the favicon of admin pages.


What Are “Conditional Tags”?

They are basically “yes-no questions”: They return only TRUE or FALSE when you use them. We use them in if statements – if the statement is TRUE or FALSE, we can process our code according to the answer.

You can see all the Conditional Tags in the WordPress Codex.

Now, let’s get to the fun part! There are ten great functions using Conditional Tags in this article.


Function 1. Display a Popup Message in the Front Page With is_front_page()

Greeting the visitor from the home page could be pleasant for the visitor, or you can place a warning for scheduled maintenance, or you can show a horrendous popup ad. Whichever you need to do, here’s how you do it:

First, you need to get the Colorbox jQuery plugin here. Get colorbox.min.js from the “colorbox/colorbox” folder and the colorbox.css (and the corresponding “images” folder) to a “colorbox” folder inside your theme folder.

Then, you need to create a colorbox.load.js file in order to load the popup. Place this file into the “colorbox” folder, too:

jQuery(document).ready(function($) {
	var $popup = $("#mypopup");
	$.colorbox({href:$popup});
});

After that, place your popup HTML code (with the “mypopup” ID for CSS) inside your theme’s index.php file and hide it in your style.css file (with “#mypopup {display:none;}“).

function front_popup() {
	if(is_front_page()) {
		// load colorbox.min.js
		wp_enqueue_script('colorbox-js', get_template_directory_uri().'/colorbox/colorbox.min.js',array('jquery'));
		// load colorbox.load.js
		wp_enqueue_script('colorbox-load-js', get_template_directory_uri().'/colorbox/colorbox.load.js',array('colorbox-js'));
		// load colorbox.css
		wp_enqueue_style('colorbox-css', get_template_directory_uri().'/colorbox/colorbox.css');
	}
}
add_action('wp_head','front_popup');

Paste this into your functions.php file and you’re good to go!

Note: In order to make your popup go away, you need to add a link inside your popup. This will do just fine:

<a href="javascript:$.colorbox.close();">Close</a>

Function 2. Include Extra CSS and JS Code Inside a Specific Page With is_page()

You may need to load some external JavaScript or CSS files for a specific page – like your “About” page or a download page for your product. Yes, you can also include them in your content but it’s not good practice. Here’s the good practice:

function extra_assets() {
	if(is_page(123)) { // '123' is the ID of the page we are checking for
		wp_enqueue_script('my-script', get_template_directory_uri().'/some/path/in/your/theme/folder/script.js');
		wp_enqueue_style('my-style', get_template_directory_uri().'/some/path/in/your/theme/folder/style.css');
	}
}
add_action('wp_head','extra_assets');

Like the first example, adding this into your functions.php file is enough. (Don’t forget to change the “123” number with your page’s ID!)


Function 3. A “More From This Category” Section for Posts in a Special Category With in_category()

It’s not always necessary, but you may need a “More From This Category” section for a category (but not the other ones). Say, you have a “News” category and the other categories are not suitable for the section we’re going to create. The Conditional Tag in_category() will help us with that:

function more_from_category($cat_ID) {
	if(in_category($cat_ID) {
		$posts = get_posts('numberposts=5&category='.$cat_ID);
		$output = '<h3>More from this category</h3>';
		$output.= '<ul>';
		foreach($posts as $post) {
			$output.= '<li><a href="'.get_permalink().'">'.get_the_title.'</a></li>';
		}
		wp_reset_query();
		$output.= '</ul>';
		echo $output;
	}
}

Build this function as you like and add it into your functions.php file. Then, go to the single.php and place the code (<?php more_from_category(123); ?>) where you want the section to appear. All you need to consider is to place the code inside The Loop. That’s all!


Function 4. Remind Yourself (Or Your Authors) That You’re Still on the Preview Page With is_preview()

This is not a must (after all, we’re just learning examples for these Conditional Tags) but it might be a good idea to remind yourself (or your authors) that the page displayed is the “preview” page. Add this into your theme’s functions.php file:

function preview_warning() {
	if(is_preview()) {
		echo '<div id="preview-warning">Remember, you\'re still on the Preview page!<div>';
	}
}
add_action('the_content','preview_warning');

Of course, this is not enough – you need to edit the style.css to give a shape to the warning text. Something like this:

#preview-warning {
	background:#800;
	line-height:50px;
	font-size:30px;
	font-weight:bold;
	text-align:center;
	position:fixed;
	bottom:0;
}

There you go!


Function 5. Remove Certain Elements From Your 404 Pages With is_404()

This one is the easiest tip of all. I don’t think it even needs an explanation – just wrap those “certain elements” (things that you don’t want to show on your error pages, like ads) with the code below and you’re good to go!

if(!is_404()) {
	// Here comes the "certain elements". It's that easy. Seriously.
}

Function 6. Never Show Auto-Generated Excerpts Again With has_excerpt()

I just hate the auto-generated excerpts. So I remove them – with the code actually provided from the Codex:

function full_excerpt() {
	if (!has_excerpt()) {
		echo '';
	} else { 
		echo get_the_excerpt();
	}
}

Add this into the functions.php file and then all you have to do is change the instances of the_excerpt() with full_excerpt().


Function 7. List Only the Post Titles (Instead of Full Posts) on Date-Based Archives With is_date()

Sometimes, listing just the titles is more than enough on certain archive pages – like the date-based archives. So, for example the Conditional Tag is_date(), we will get rid of the stuff in The Loop except the title.

This is kind of tricky since the archive.php files are different in each theme. (And if there’s a date.php file in your theme, you should edit that one.) Look for The Loop in the code and change the code inside The Loop with this:

if(is_date()) {
	// If your theme uses h2 headings for post titles, use h2. If it uses h1, use h1.
	echo '<h2>'.the_title().'</h2>';
} else {
	// ...
	// The original code inside The Loop
	// ...
}

Function 8. A Separate Favicon for Your Admin Panel With is_admin()

This tip could be quite handy if you like to work with 20 open tabs, all for your blog. Just edit your favicon a little bit and save it as adminfav.ico – for example, my admin panel favicon is just the red version of my original favicon.

Anyways, here’s how you do it:

function admin_favicon() {
	if(is_admin()) {
		echo '<link rel="shortcut icon" href="'.get_bloginfo('url').'/adminfav.ico" />';
	}
}
add_action('admin_head','admin_favicon');

Function 9. Show a Default Thumbnail if the Post Doesn’t Have One With has_post_thumbnail()

This is kind of a must for a good theme. If you have any part in your theme where the featured images’ thumbnails are shown, you should replace the the_post_thumbnail() functions with the code below:

if(has_post_thumbnail()) {
	the_post_thumbnail();
}
else {
	echo '<img src="'.get_template_directory_uri().'/images/default-thumb.jpg" alt="'.get_the_title().'" class="default-thumb" />';
}

This way, you can keep the consistency of your theme’s looks.


Function 10. Show a Special Menu for Your Logged in Members With is_user_logged_in()

If you use the membership system in WordPress and have members, you may want to create a special menu just for your logged in members. Here’s how:

function member_menu() {
	if(is_user_logged_in()) {
		echo '<div class="member-menu"><h2>Member Menu</h2><ul><li><a href="#">First Menu Item</a></li><li><a href="#">Second Menu Item</a></li><li><a href="#">Third Menu Item</a></li></ul></div>';
	}
}

This is a standard “title & list” code, you should play with the code to make it like your sidebar divs and then place the code <?php member_menu(); ?> in your theme’s sidebar.php file.

Also, this is just an example, but ideally you would use WordPress custom menus with wp_nav_menu() here. One standard and one for members, then you can continue to manage them from your WordPress admin dashboard. You can read more about the wp_nav_menu() function here.


Any other ideas?

These were my favourite 10 ideas to use Conditional Tags. What about yours? If you have anything to share, please comment below so we can extend this post with more ideas!

Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://twitter.com/mrxxiv Terrence Campbell

    I thought I couldn’t use many conditional tags in functions.php.

    Amazing btw!

  • http://wp7app.de Thomas

    Great post, thanks.
    What would be the way to go if you want to show a particular widget only on the front page?

    • http://kg69design.com kg69design

      You can do this like that (place the code in appropriate theme’s file):
      if(is_front_page()) {
      echo do_shortcode( “[your_shortcode param='value'...]” );
      }

  • http://www.leachcreative.com Andrew

    This is a pretty great collection of conditional tag usages. Thanks for sharing.

  • http://www.ubuntubrsc.com/ Julian Fernandes

    Great post! I usualy like to use it for social buttons, so in front page only facebook is loaded, because i have it on my sidebar, and on single twitter and g+ are loaded too (:

    But i do have a question: is it possible to disable a plugin if the user is on a mobile phone? There is a conditional tag called “is_iphone” iirc, but i don’t know how to use it so a certain plugin won’t load. It would be great, since i made my mobile theme in a way it have no JS at all.

  • http://www.amazing-web-design.co.uk/ Joe Elliott

    Hi Baris,

    Thanks for the tips, need to try some out!

    Thanks
    Joe

  • http://www.designsmix.com/ Ulra

    great tip with auto-generated excerpts. thanks for article.

  • zzap

    Hi, great collection of functions. Just one thought, though. Maybe I’m wrong but I believe there’s a small error in Category function on line 7.

    $output.= ‘<li><a href=”‘.get_the_title().’”>’.get_permalink.’</a></li>’;

    Shouldn’t permalink and title change their places? Like this:

    $output.= ‘<li><a href=”‘.get_permalink.’”>’.get_the_title().’</a></li>’;

    • http://wp.envato.com/ Japh Thomson
      Staff

      Hey Zzap, well spotted! Thanks for pointing that out :) I’ve fixed it up now.

      • zzap

        I’m glad I could help.

        I’ve learned from WPTuts about WordPress more than from anywhere else, it’s good to be able to give a little something in return.

        Keep up with great work :)

        • http://beyn.org/ Barış Ünver
          Author

          Whoops! Tiny mistakes like this embarass me :(. Thanks for spotting though :).

  • http://angelofreproduction.net Jay Cassano

    Thanks for this post. I didn’t quite realize that using the built-in conditional tags was so simply. That’s great to know. A specific question on the first example: what tag would one use or how would one implement a way to only show the pop-up to non-logged in users on the front page?

  • http://www.customicondesign.com custom icon design

    absolutely good tutorials. I like wp.tuts because it indeed has so much great article there.

  • Kyle

    I don’t use conditional tags all that much, but one thing I find them very useful for is if you have multiple headers, footers, or sidebars for your site, using a conditional tag to target pages and display the appropriate pieces. Basic stuff but holds a lot of possiblities

  • http://freakify.com/ Ahmad Awais

    Hey Barış Ünver,
    Nice post ! Loved the excerpt hack :)

  • http://www.technoszene.com/core/ Willi

    Nice Post, love your Tutorial

  • Pingback: HostNine Weekly Round-Up: 6/18 – 6/22 | HostNine Company Blog

  • http://xn--danielnuez-09a.com Daniel Nunez Chinchilla

    I always wanted to know if something like this is possible:

    If ($Color_Custom_Field = ‘red’) {
    some html A
    }

    else {
    some html B
    }

    Sorry for my lack of programming knowledge, but if this is possible it would be great for me! :P

    • http://beyn.org/ Barış Ünver
      Author

      Hey Daniel. If you’re going to use something like that, you need to set the value of $Color_Custom_Field first, with get_post_meta(), like this:

      $Color_Custom_Field = get_post_meta(get_the_ID(), ‘name_of_your_custom_field’, true)

      Add this code into your own and use it inside The Loop.

  • Pingback: Tweet Heat - The hottest Tweets of the Month [June 2012] | Inspired Magazine

  • Pingback: WordPress and Web Development: Top Resources for August 2012 - ManageWP

  • Peter Netz Lassen

    Hey!
    This is a cool read :)
    This makes it so easy… I always wanted to know how to easy check for any conditions on different types of paged and not have a huge javascript loading on every page or some php function!
    This is brilliant – And the easy examples does it for me… I am inspired and ready to take on my WP with new passion!!

    Thanks mate!

    Peter

  • http://www.ruzzleonline.nl Willem

    Good afternoon,

    Do I have to put function 9 into my functions.php to let it work?

    Kind regards,

    Willem