WordPress Conditional Tags: is_single()
- Posted On: April 23rd, 2007
- Filed Under: Web Design, WordPress
- Tagged As:
I've been working on a template for a new site and recently had to add a special function to the sidebar.
Because I expect this site to see a lot of traffic in the archives I wanted a way to promote the new posts when visitors were looking at old ones. Something I've done in the past, which has always worked nicely, has been the inclusion of a list of the most recent posts in the sidebar. Using a WordPress conditional tag and the WordPress Loop we can setup an item to show off the recent posts and hopefully push traffic through some of the newer sections of the post.
This post is part of a series which will outline the steps you can use to get your recent posts listed in your sidebar. With a little bit of playing around you can also use these methods to accomplish some other goals - but I'll leave that up to you for now. In this post we'll cover the basics of the is_single Conditional Tag.
Having WordPress Recognize a Single Page
WordPress' is_single() is a function with two possible results: True or False. Depending on certain outside variables WordPress determines what value to return and then proceeds based on your lead.
Take the following code for example:
<php if (is_single()) { echo "This is a single post"; } ?>
Placing the above code into your sidebar will result in the phrase "This is a single post" appearing on any page that serves a single post. With no arguments (when the parentheses are empty) WordPress simply tests to see if the page being served is a single post. By adding an argument to the code you can test for more specific events. Using "is_singe('17')" for example would test to see if the post being displayed has the id number "17."
You could alternately use post title or post slug inside is_single() to test for the same event.
What if we Don't Want a Single Page?
With a slight alteration you can also test to see if the page IS NOT a single post or DOES NOT meet the other criteria. Because is_single only returns values of TRUE or FALSE you can occasionally use it to place items on pages that aren't single posts. While you wouldn't use it to test for the index template or a category page it's ideal for finding everything that isn't a single post.
Simply change the first part of the phrase like so:
<?php if(!(is_single())) { echo "This isn't a single post"; } ?>
By adding the exclamation point above we're able to test for anytime that is_single doesn't return TRUE. On a single page, category page, or anything other than a single post we'll see "This isn't a single post."


