How to Use WordPress Conditional Tags

by Andrew Norcross · 65 comments

Let’s say you want your Recent Posts to appear on one specific page of your WordPress website. To accomplish that, you would create a special function and hook the Recent Posts into place.

I know those two words—function and hook—are scary, but bear with me. It’s not as hard as you think… especially when you follow this step-by-step tutorial.

So, how can you get Recent Posts to appear on one page, but not another? Well, you would use what nerdy programmers like myself call conditional statements, which is really just tech speak for “if, then statements.”

How do “if, then statements” work? Well, quite simply, if you’re on page 1, show Recent Posts, else, if on any other page, don’t show Recent Posts. Logically, it makes sense, right?

The question is, what’s the easiest way to incorporate these conditional statements into the Thesis Theme Framework? Keep reading.

The Power of the Thesis Custom Functions File

One of the great things about Thesis is the custom_functions.php. Instead of modifying or duplicating information across multiple files, which is required in some themes, you can write one function, use Thesis Hooks to get it where you want it, and bam, you’re done. But, now, let’s get down to business.

How to Use WordPress Conditional Statements in the Thesis Theme Framework

From this point forward, you’ll be working with your custom_functions.php file. Please be careful. If you paste or tweak the code in incorrectly, you’ll need access to your FTP to fix it. Also, please be sure to backup your custom_functions.php before you get started; that way, if you make a mistake, you can revert back to your original with no problems.

To start, let’s look at a basic Thesis function that adds a list of recent posts to the sidebar. To do that, you would include the following code in your custom_functions.php file:

function recent_post_list() { ?>
    <li id="recent_posts" class="widget">
    <h3>Recent Posts</h3>
    <?php query_posts('showposts=5'); ?>
    	<ul class="recent">
		<?php while (have_posts()) : the_post(); ?>
		<li><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></li>
		<?php endwhile;?>
		<?php wp_reset_query();?>        
        </ul>
    </li>
<?php }
add_action('thesis_hook_before_sidebar_1', 'recent_post_list'); // Recent Posts

Real simple. But let’s say you only want that to appear on the main page of the site? Adding 1 line is all it takes

function recent_post_list() { 
    if(is_home()) { ?>
        <li id="recent_posts" class="widget">
        <h3>Recent Posts</h3>
        <?php query_posts('showposts=5'); ?>
    	    <ul class="recent">
		<?php while (have_posts()) : the_post(); ?>
		<li><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></li>
		<?php endwhile;?>
		<?php wp_reset_query();?>        
            </ul>
        </li>
<?php
    }
}
add_action('thesis_hook_before_sidebar_1', 'recent_post_list'); // Recent Posts	

That’s it!

Now, if you take a look at the code, do you see the second line of the function that includes the conditional tag is_home? Also, take note of the 2nd bracket at the very end. Forgetting that will cause the function to error.

Ok, so now say you want it everywhere except the home page. Well, WordPress conditional tags allow for both inclusion and exclusion. Here’s the code for your custom_functions.php file:

function recent_post_list() {
    if(!is_home()) { ?>
        <li id="recent_posts" class="widget">
        <h3>Recent Posts</h3>
        <?php query_posts('showposts=5'); ?>
    	    <ul class="recent">
		<?php while (have_posts()) : the_post(); ?>
		<li><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></li>
		<?php endwhile;?>
		<?php wp_reset_query();?>        
            </ul>
        </li>
 <?php
    }
}
add_action('thesis_hook_before_sidebar_1', 'recent_post_list'); // Recent Posts

Adding the exclamation point causes the function to trigger everywhere other than the home page.

So, are you getting the idea? Here are a few other examples of conditional tags that you can use in your Thesis file:

if (is_home() || is_archive())

This would trigger either on the home page or on any archive page (category, tag, etc). Putting the two solid lines in between makes each conditional tag stand alone.

if (is_single() && in_category('awesome'))

This would trigger ONLY on single posts in the category named "awesome".

if (is_page('about-me')) 

This would trigger on just the "about me" page. Take note, when I target a page, you have to use the page-slug, which is what appears after .com/

if (is_category(array('awesome','tutorials')) 

Whoa, I included something else here, and it's called an array. What's the deal with Arrays? Well, when you include an array, it allows your code to target several different things at once.

For example, in the above example, the recent posts would trigger on the category archive page for "awesome" and the category archive page for "tutorials."

*A note about categories* Deciding when to use is_category and in_category can be tricky. Usually, it takes some trial and error to get it fine-tuned to that level of detail. As a rule of thumb, use in_category in conjunction with is_single.

Can You Add Anything Other Than Recent Posts?

Absolutely. All you have to do is replace the HTML, the code that falls between the the opening <li id="recent_posts" class="widget"> and closing </li>. For example, you could include the HTML for your ad tags, and then, target your ads to specific pages. It's that easy.

The Bottom Line

That wasn't so hard, was it? If you have any questions, refer to the WordPress Codex to see all the different tags that are available (there are many). Or, you can leave a comment below and I'll pop in here to answer some questions!

About the Author: Norcross is a full time freelance WordPress developer and tattooed web nerd in Tampa, Florida. You can check out his work here, or you can see random swearing and pictures of an awesome "littleman" on twitter. He's also a featured Thesis Designer.

If you enjoyed this article, enter your email below to get free updates!

{ 61 comments }

Genuine Chris Johnson

I did this this for the first time this weekend using widget logic. That’s a good, safe place to start doing this stuff…to get stuff to appear in one place and not another. Everything worked just fine, the Codex was solid and I got this on the second try.

Norcross

I agree, the Widget Logic plugin is great for sidebar items. It allows the same functionality without touching your functions file.

Jhay

While the Widget Logic plugin does save us the trouble of editing code, does it work well with blogs that are using page caching?

Norcross

It should, but I’m not the server speed / cache expert. Willie Jackson would know better than I would

Willie Jackson

“Work well” is little nebulous and subjective, but the only thing widget logic does is conditionally display (or not display) its content. I can’t think of anything it does that might interfere with caching. So yes :)

Jhay

Thanks! Though I’ve read somewhere in the WP forums that the Widget Logic conflicts with some plugins that allow PHP code to be executed from within.

So I’d be taking the Thesis way of doing it via the custom_functions.php

Dustin Dyer

Perfect! I was wondering how to do this just the other day.

Nanette

Great article. Please give us more like this.

Wim

Thanks for this information! It is truly remarkable what people will share on the Internet.

I now know that I really did make the right choice joining the Thesis crowd. In the short time of my membership I have gained incredible knowledge which I am sure I would not have gained anywhere else in such a short time.

This article is sure to help me tremendously in the future.

Josh Giese

Thanks for the tutorial. It’s very straight forward. I’m sure that it will help a lot of people.

Sharon

Excellent information! Thanks for breaking things down and making it so easy to understand.

I’m wondering if you can use conditional tags for Nav Menus? I know that Thesis only supports one WP menu, but I’ve seen sites (even this one) change their menus based on the page/category. How would that work?

Norcross

By default, Thesis supports a single menu. However, you could add additional ones with a function, then trigger them with a conditional tag.

Dan

Great article.

Been after something along these lines for ages. I would like to show recent posts underneath my teasers – but only show the recent posts in the same category as the post for which the teaser belongs to.

Is this possible?

D

Norcross

You want them on the home page below each teaser?

Dan

Thanks for the relply.

Yeh. Just like – http://www.telegraph.co.uk/

Norcross

This would certainly be possible, but it really wouldn’t fall under the setup with a conditional tag. It would be using the thesis_hook_after_teaser hook along with a function like this http://pastie.org/1300919

I haven’t tested the code completely, but it should do the job.

Dan

Sorry for my ignorance – I assume this code goes in custom_functions.php?

Dan

If so, just put that in there, it broke, and had to clear it via ftp.

D

Norcross

Sorry, that wasn’t meant to be a complete function. It was just the actual loop to create the related posts. Here’s a full function that should do the job. I did a quick test on a dev site and it worked.

http://pastie.org/1301534

Dan

Brilliant. Works perfectly, wont even pretend i understand how it works. Cheers!

As an aside, is it posssible to style this element independently? I.e. how do i remove the bullet point and change the font without other elements changing too.

Again, thanks. Hopefully this will be of use to others too.

D

Norcross

Yep. Here’s a slightly modified version of the function that includes some special div classes you can trigger with CSS

http://pastie.org/1302699

And some sample CSS (you’ll have to play with the styling to get what you want…you’re now venturing into my hourly rate!) http://pastie.org/1302708

Jaxrolo

Great Piece of code. I love it. Thanks!

Norcross

Glad it’s workin for ya. You might wanna style the CSS a bit though for a better look.

Brad

Sweet tutorial Andrew, thanks!

Willie Jackson

Nice post mate. A mastery of conditional tags in WordPress is essential for anyone wanting to deliver compelling client designs…or even get the most out of their own sites. Here’s hoping this empowers the masses.

Lucky Balaraman

This is good stuff… thanks for it. Glad to know that the Thesis team does not frown upon users messing with their functions :)

Norcross

I’d go so far as to say they encourage it :) That’s the real power of Thesis in my opinion.

Stan

Hey Andrew, I read an article at Prelovac com about listing post tags on a single page (for SEO purposes – silo site structure – tags page as SE magnet) when you wrote this article. Since then I was trying to do it but I keep failing. Can you please advise how to list all post tags on one page (/tags). I feel it’s very simple but some of us are not as skilled with code… yet ;) I do realize your examples are about listing in widgets but it must be very close to this solution (changing the class I guess…).

Thanks

Stan

Norcross

The side widget was just an example. I actually use this most for items that are page or area (i.e. single post) specific. Here’s a function that’ll list all the tags. Just be careful, a lot of tags could time out. Not sure how many is ‘too many’ so you’ll have to test and see.

http://pastie.org/1302864

Kev

I’m really pleased you’re adding tutorials on the nitty-gritty of getting under the bonnet of Thesis – I would be EXTREMELY happy to see a tutorial on custom page templates.

Norcross

With the custom loop API, I’ve found myself needing custom page templates less and less.

mark williams

Have found widget logic easy to use and great for those right column widgets that need to relate that particular page. Then u can just click and drag when not needed ;)

Bret Phillips

I dig this post. You’ve done a good job of making something that is easy yet seems difficult, seem easy.

Jhay

How can I use this code to do the following:

1) Display the recent posts from all categories on the home page,

2) On a single post page, it would display only the recent entries from the same category of the current post

Doing #1 is pretty simple based on the tutorial. But #2 is quite tricky. Any help would be greatly appreciated. :D

Norcross

Number #1 is the function used in the post example :)
For #2, this function should handle it. http://pastie.org/1308660

Jhay

Great! I’ve got everything working as it should.

One last thing, how can I make the heading in #2 to reflect the name of the current category, like “Recent Posts in [category name]” instead of the default text: “Recent Category Posts.”

Jhay

Update: I’ve got all issues fixed. :)

Btw, I removed the first “<?php" snippet on the first line of the code for #2. It caused an error the first time I used the code on my blog.

Thanks so much.

Rocky

I checked the codex you referenced but I couldn’t find the answer to my problem so I thought I ask you.

I’m running a MS WP. I only want some content to show up on the main domain blog (i.e. domain.com), but not on the other MS blogs (domain.com/MS-blog/). I tried using the “is_home()” and “is_front_page()” but I think because each blog has a “home” it doesn’t quite work.

Do I have to hack my conditional with a $_SERVER['REQUEST_URI'] type statement?

Norcross

You can do it, the syntax is just slightly different. You would need to know what the blog ID of the particular site within the MS installation is. Try this:

global $blog_id;
if( $blog_id == ’2′ ) {
//do some comment stuff for blog 2
}

Rocky

Thanks Norcross, it worked like a charm!

Gerry

Its not working for me, I get recent posts and then everything else underneath, not what i wanted :-(

Norcross

The function (pulling recent posts) was just an example of what can be done. The focus was showing the different uses of conditional tags.

Andrew Walsh

Hi, great tutorials. I really admire Thesis themes. I’m just trying to learn a little bit about theme design myself, but right now I only have a basic understanding of PHP.

Is the syntax you give here specific to Wordpress? I’ve always been a little confused about where exactly they define what a “category” or “archive” is, for example.

I realize this isn’t very specific, and I might not be making sense. If you maybe had a recommendation for a place to read about beginner’s PHP, that would be awesome! (So far I just have gone through the WP Codex)

Brian

Will this work with pulling recent posts onto the homepage body? as opposed to the sidebar?

My homepage is running on the ‘no sidebar’ template and I’d like to pull a list of recent posts at the bottom of it.

Norcross

The function itself is agnostic towards where it it placed. The conditional only determines when it’ll trigger, and then you would use one of the Thesis hooks to determine where. In a comment to Dan above, I gave him some code that pulls “related” posts in the body area. That should give you a good start.

Nicole Powel

hey

thank you for the tutorial
I am trying to find the footer.php file in Thesis, as I want to paste a code just below the tag, but I haven’t been able to do it so far.

Can you help, please?
Thank you, Nicole

Norcross

There is no “footer.php” in Thesis. You want to look at the available hooks to place whatever code you’re looking for, or the settings panel has a place for placing analytics code.

Nicole Powel

code should go just above the body tag

Brooke

I’m trying to add a hook to some pages and not all. Ideally I’d love it to be in a custom template so the client can choose which pages have the different hook. Otherwise, putting it in the custom_functions is great. I just can’t get the syntax right!

Norcross

To set a function in a particular page, you would want to do if (is_page ( 'page-slug' ) ) if you’re looking to do a few pages, you’d want if (is_page ( array ('page-slug', 'another-page-slug', 'a-third-slug' ) ) ).

I recommend reading up on the codex link in the post for the full range of options and syntax.

Brooke

Worked like a charm. It was the ‘array’ I was missing. Thank you so much, sorry for being such a PHP noob!

Rob @ Atlanta Real Estate

Would if I wanted to add the Google +1 button to all my pages AND posts? Here’s the code for adding it to all the posts:

function google_plus_one_output() {
if (is_single()) { ?>

<?php }
}
add_action('thesis_hook_before_post', 'google_plus_one_output');

THANKS!!

Regina

Oh. My. Goodness. Do you know how helpful this would have been if I found this a month ago. I guess I shouldn’t have paid for Thesis if I wasn’t going to use its resources! I should have looked here first. Thank you so much, this will help me so much and save me a ton of frustration. Keep up the good work!

david

Norcross -

Pulling my hair out as a real estate agent trying to code a site – but loving my 2 weeks with thesis so far! would appreciate any help on….
I’m using a rotating image widget (vslider) to appear above my content with a single line of code:

add_action(‘thesis_hook_before_content’, ‘vslider’) ;

It works great – except it shows on every page – I only want it on the home page – I keep trying to add the conditional statement into the code but always get some type of error message – i’ve tried lots of different combinations-ex
if i use:
function vslider() {
if(is_home()) { ?>
<?php
}
}
add_action('thesis_hook_before_content', 'vslider');

I get…..
Fatal error: Cannot redeclare vslider() (previously declared in /public_html/wp-content/plugins/vslider/vslider.php:867) in /public_html/wp-content/themes/thesis_181/custom/custom_functions.php on line 17

ANY help much appreciated!

Norcross

You’re declaring the function twice. Remove the 2nd add_action

Etre Heureux

I’ll do that when I’ll more at ease with wordpress. I’m just beginning now
but thanx for the tip

Rentier

Great article!
Would you know how to move the previous and next post from bottom to top of the page, just above the current read post?
I’ve searched for that info but I couldn’t find
thanx

David

Great tips Andrew! The “if, then statements” take me back to my old programming classes.

Though all the programming has changed, that logical mindset still helps when customizing your blog.

Mia

Thank you so much I had an idea of conditional codec but i just didnt know how to use the correct syntax within header code and you show it here! Thank you again!

Dasha

Hi,

I’m trying to do something similar for future posts:
- if post status=future show a message: “please wait until this date”
- if post status=publish show the title and content of this post.
Can anyone help? Much appreciated since I’m a beginner.
Thanks!

Jason

Very helpful. I looked at the wordpress codex and it does not appear to speak about the inclusion/exclusion conditions.

I now the the “!” makes the difference

;)