Code

WordPress Tip: How to create a ‘Top Ten’ list

Ed: This article is part of the 21 Days of WordPress Tips

Most bloggers have their favorite articles they’ve written. And while these may not be the most commented or most linked to, they are the best in displaying what the blogger writes about and his expertise. So what’s the best way to highlight these in a list on the home page or sidebar?

One option would be to hard code the links. However, as with most problems in hard coding anything, it’s going to be hard to change and will cause problems if you change the anything in the future.

Here’s an easy way to use custom fields and query_posts() to create your ‘Top Ten’ list:

1. Setup a custom field called ‘topposts’

1.a. You can do this by using the normal custom fields portion of the write/edit page. In this case, the key will be ‘topposts’ and the value will be ‘1’.

custom11

1.b. Or, if you use the More Fields plugin I reference in this post, you can just create a simple check box in the sidebar of your write/edit page.

custom2

2. Add the code to your theme

Once you’ve gone through and selected all the articles that you want in your ‘Top Ten’ list, we have to add the query_posts() call to your theme.

Thankfully, there is a custom field reference for query_posts(). Here’s the code:

<h3>My Top Ten Posts</h3>
<ul>
<?php
query_posts('meta_key=topposts&meta_value=Yes&showposts=10');
if (have_posts()) : while (have_posts()) : the_post();
?>
<li><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></li>
<?php endwhile; endif; ?>
</ul>

Just drop that code in on your sidebar or home page and you’ll have your top ten posts showing.

WordPress Tip: How to secure your installation

Ed: This article is part of the 21 Days of WordPress Tips

There have been a lot of security issues with WordPress in the past and, if you don’t setup your installation correctly, it can be wide open to hacker attacks. Here’s a few things I’ve seen:

  • Embedded spam links – A hacker will add code to your site that will show hundreds of spam links in the footer/header of your site. This is often hard to catch as the code will only show these links to Google and other search engines so you only realize something is wrong when your traffic numbers tank because you’ve been pulled from the search results.
  • Phishing pages added to your site – Spammers that are sending out those phishing emails trying to trick people into giving away their bank account information will add html pages to your site that they then link to. This is big time bad news as you’re IP will get flagged and traffic will again nose dive.
  • Database edited or deleted – In many instances this could be the worse thing to happen. You can recover from getting pulled from search engine results, however you may not recover from your database and files getting deleted. (I should also mention here that you should be doing regular backups of both)

While there are plenty of things that hackers can do when they gain control to your site, those are the most common ones I’ve seen. So how can you possibly defend against these attacks when even Al Gore’s site is getting hacked?

Follow these tips and you’ll be well protected:

1. Download and install the WP Security Scan plugin

This is the best security plugin I’ve come across. It checks several of the common things that make your site easily hackable (I go over a couple of these below), it scans all of your directories to make sure they have the correct permissions set and it has a simple tool for creating extremely strong passwords.

If you only do one thing to help protect your WordPress site from hacking, download and install the WP Security Scan plugin.

Tip: The popularity of WordPress often works against it. Since the default installation of WordPress does a lot of things the same way, hackers often use this as an advantage. For instance, everyone has an “admin” user, has a table prefix of “wp_” and puts the version of WordPress in the <head> of the HTML. This is knowledge that hackers use to find vulnerabilities in your site. The above plugin fixes some of it and only checks others. Below I address how to fix several of these issues.

2. Change your default “admin” user

Open up your database administration tool. In most cases this will be phpMyAdmin. Open up the “users” table and edit the row for “admin”. Simply change the “user_login” field to something else and save it.

secure

This will protect your site from brute force password attacks. If there is no user “admin” then the hacker will be forced to guess both the username and the password which is virtually impossible.

3. Change your table prefix from “wp_” to something else

Be very careful with this one and, as with any time you are making changes, backup your database.

What we are going to do here is change all your table names from wp_options, wp_users, etc to something like wp_3jd73_options, wp_3jd73_users, etc. This will make it extremely difficult for a hacker to run rouge SQL queries since they will not have the name of the tables.

Thankfully, this is very easy to do if you followed my advice in step #1. There is already a tool in the WP Security Scan plugin to do this.

Also, be sure to check that all your plugins are working correctly once you’ve made this change. Some very old or poorly written plugins may be directly referencing your tables with “wp_”. If this is the case, I suggest either deleting the plugin all together or upgrading to the newest version.

4. Move the wp-content folder to a different location

Moving your wp-content to a different location helps in a couple different ways.

First, and most importantly, it guards against hackers trying to access the folder.

Secondly, it makes upgrading your WordPress installation a breeze because you won’t accidentally overwrite you wp-content folder if you upload all the WordPress core files at once.

Once you’ve made the move, you need to let WordPress know where it’s located now.

Add this line to your wp-config.php file:

define('WP_CONTENT_DIR', 'http://www.mysite.com/7h3j6d/wp-content');

As with step #3, you may have some plugins that are directly referencing wp-content/ in the root of your site. So be sure to check all the functionality and delete/upgrade your plugins accordingly.

Lastly, use some common sense

Most of the security issues with WordPress (including the ones I’ve dealt with) can be prevented or easily fixed by doing all the normal things that everyone should. Keep strong passwords, backup regularly, keep WordPress core/plugins up to date, etc.

By following these tips you’ll have a safe and secure installation of WordPress that will make it so difficult to find a vulnerability that it will keep the hackers moving on to someone else’s site.

WordPress Tip: How to change the domain name

Ed: This article is part of the 21 Days of WordPress Tips

While it’s nice to build a new site behind a coming soon page, in most cases when you are designing a new site you’re doing it while a current site already exists. There are several different ways to do this, but in most cases you’ll test it at a demo domain name and then, when you launch, you’ll need to switch everything over to the live domain name. Unfortunately, this is not as simple as it sounds. Below are a few of the common pitfalls and how you can get around them safely.

Caution: Some of my tips below use SQL statements that change a lot of database content at once. While I use them on a regular basis with no problems, I don’t guarantee that you won’t screw something up. Please backup your database and wp-content folder before doing anything. You have been warned.

1. Hard coded links in your theme This will not be a problem 99% of the time, however if you’re theme was built custom or you have made changes to it, there might be places where you hard coded a link (i.e. http://mysite.com) instead of using one of the WordPress functions to call it (i.e. get_option()).

If this is a problem, just go through and replace each of the hard coded links with:

<?php echo get_option('siteurl'); ?>

This will pull your URL from the database. Once these changes are implemented, you’ll never need to touch them again even when you change the domain of your site.

2. All the links use the demo domain name

WordPress stores the domain name of your site in the database table called wp_options. If you try to login to your site on the new server it will automatically redirect you to the old domain name that is stored in the database.

What you need to do is open up the phpmyadmin for your server and run this SQL query with the relevant pieces changed to your situation:

update wp_options set option_value = replace(option_value,'http://demo-url.com','http://live-url.com');

This will change all of the references in your wp_options table to the live URL. This will make it so you can now login to the Dashboard and all of your links using the function from #1 will work as well.

Tip: To combat hackers and make the WordPress installation more secure, your options table may not be named exactly “wp_options”. Be sure to check your database first to make sure you have the table name correct.

3. Broken permalinks

When you set your permalinks under the Settings -> Permalinks page of the WordPress dashboard, it changes settings in your .htaccess file in the root of your site. So when you are running your site under a different domain name, these will often no longer work.

Thankfully this is a very easy fix. Merely click the “Save Changes” button on the Permalinks page to reset and it’s done.

4. Post/page images and files no longer load

Assuming you added content to the site prior to launch, you probably uploaded some images (or other files) with the media uploader and added them to the post content. Unfortunately these are now hard coded to the demo domain name.

Thankfully, there is any easy fix that you’ve already had practice with in step #2 above.

Log back into your phpmyadmin and run this SQL statement:

update wp_posts set post_content = replace(post_content,'http://demo-url.com','http://live-url.com');

This will change any references to the demo domain name in your content, whether an image, link, PDF, etc., to the live domain name.

And you’re done

Your site should now run at the live domain name with no problems. However, since hosts and test environments vary greatly, you may run into a problem I don’t mention above or one of my tips may not work for you (i.e. your host doesn’t have phpmyadmin installed). If this is the case, leave a comment below and I’ll do my best to help you out.

WordPress Tip: How to add author biography information to your posts

Ed: This article is part of the 21 Days of WordPress Tips

If you’re maintaining a WordPress blog that has multiple authors you may want to let them attach a little biography information to everything they write. Here’s the steps to do this simply.

1. Have your authors login to the WordPress dashboard and click on their name in the top right corner.

author1

2. Then scroll down to the “Biographical Info” textarea under “About Yourself” and fill it in.

author21

Now that they have their bio information in, it’s your job to add it to the bottom of each post. The template tags that we will be using are the_author() and the_author_description(). In this walkthrough we’ll be adding the author information to the single.php template file so it will only show on individual posts, but you can easily use this walkthrough to show it on other areas of your site.

3. Open the single.php file of your theme and find the the_content() function call. We’re going to add the following code directly underneath. We’ll also wrap it in an additional <div> tag with a class of author_bio so we can add a little CSS pizazz later on.

<div class="author_bio">
<strong><?php the_author(); ?></strong>
<p><?php the_author_description(); ?></p>
</div>

author3

Save and upload single.php with the above changes.

At this point, if you check out an individual post you’ll see the author name and bio right underneath the rest of the post content. However, this blends with rest of the content so we’ll want to add some CSS to the stylesheet to set it apart.

4. Open the styles.css file of your theme and add this to the bottom:

.author_bio {
background: #efefef;
padding:5px;
margin:10px 0;
border: double 4px #fff;
}

Obviously you can modify the CSS elements to your liking, but this is the general idea of what you’ll see:

author4

And that’s it. You’re now giving your authors the prestige they deserve. Enjoy!

WordPress as CMS: How to use custom fields in your theme

Ed: This article is part of the 21 Days of WordPress Tips

Last week I showed you how to make custom fields easy to use for the back end of WordPress. But once you get the content in there, how do you successfully extract it and use it in your theme?

There are a few template tags that are useful in displaying custom field data:

  • the_meta() – This is the simplest way to display the custom fields. It simply prints each custom field attached to the current post showing the key and value in an unordered list. While this is a very simple solution, it gives you almost no control.

    <?php the_meta(); ?>

    Would display something like:

    <ul class='post-meta'>
    <li><span class='post-meta-key'>My Dog:</span> Ralph</li>
    <li><span class='post-meta-key'>My Cat:</span> Satan</li>
    <li><span class='post-meta-key'>My Fish:</span> Gills</li>
    </ul>

    If you want to simply list out all the custom field data for each post, this is the way to go. But if you want more control…

  • get_post_custom() – This template tag is much more useful. It returns a multi-dimensional with all of your custom field data. Using the same example as above:

    $my_custom = get_post_custom();
    echo my_custom[0]; // prints "Ralph"
    echo my_custom[1]; // prints "Satan"
    echo my_custom[2]; // prints "Gills"

    The biggest issue I have with this function is the array is returned with the keys as 0, 1, 2, etc instead of an associated array with the key being the custom field key. This causes problems when you have a lot of custom fields and you’re trying to arrange them on a page in a certain way.

  • get_post_meta() – This is the template tag I use the most for displaying custom fields. It’s simple, easy to use and gives you complete control. Here’s a typical way I’d use it in a theme:
    1. The ID of the post/page you want to show the custom field data for. In most cases you’ll be using this inside the loop in your theme where the WordPress $post variable will be set. So you can simply use $post->ID to get the right post/page ID.
    2. The custom field key that you want to pull the custom field data for
    3. Whether you want to return the results as a string (true) or an array (false). Since we simple want to print out the custom field content, we set it to true to return a string.

    if (get_post_meta($post->ID,'My Dog',true)) :
    echo "My dog's name is " . get_post_meta($post->ID,'My Dog',true);
    endif;

  • The get_post_meta() function has three parameters you can pass:

    As you can see in the above code, I wrapped the echo statement in an if statement. What this does is check to make sure there is anything in the custom field before you try and print it to the screen. That way you won’t show an unfinished statement of “My dog’s name is” if for some reason the custom field box wasn’t filled in. It will simple leave off the whole thing.

Those are three of the most widely used ways of displaying custom field data in your themes. Hopefully it will help add more functionality than ever to your next WordPress site.

Custom WordPress Arrays: Creating a favicon fueled link list

Ed: Today’s article is part of the 21 Days of WordPress Tips and was written by Adii, the WordPress Rockstar. Adii runs a boutique design firm at {radiiate} and a premium theme shop at WooThemes.

One of the main reasons why designers & developers love WordPress, is because it is simply so easy to use the variety of template tags in order to achieve a desired outcome. Having worked with WordPress for the past 2 years – at both WooThemes & {radiiate} – one of the biggest stumbling blocks I’ve encountered with WP, is that some template tags simply just don’t allow for the level of customizability that I’m after. This should however never be a problem… Let me explain…

Basically the template tags are just outputting the data that you have entered into your WP database. But since MySQL database queries and not everyone’s cup of suit, the WP core offers you easy-to-use, logical (from a layman’s perspective) template tags with a few allowed parameters to control the output. But as I mentioned above – in certain instances I’ve still found the template tags to be limiting, which has prompted me to delve a little deeper into the WP core.

So along with the more user-friendly template tags like wp_list_categories, wp_list_pages & wp_list_bookmarks, you will also find more advanced functions like get_categories, get_pages & get_bookmarks (more of these lesser known functions can be found via the WordPress Function Reference). These functions do not have an output, but instead it queries the requested data (as specified by you) from the WP database and assigns that to a PHP array. And it is when we have that “raw”, unformatted data in an array, that we can start taking control over the output thereof – thus customizing it 100% to our liking

The Example – Favicon fueled link lists

I’d thus like to take you through a foolproof example of how you can use this newly acquired knowledge about the custom WordPress functions and arrays. The example that I’m showing you will render a similar result as the “Kudo’s & Respect” links list in the sidebar on my own blog.

Generally, you would’ve been able to use the wp_list_bookmarks template tag to display the links from a specific category, but the function doesn’t allow you to display both the title & the image associated to a link. You could bypass this by displaying the description of the link in place of the title, but then the function doesn’t hyperlink that and you have no control over the HTML output (and subsequently the CSS styling) thereof. So therein is the need for a custom function… Here’s how you go about it:

Step 1 – Get the array

The first thing you want to do is to specify the array variable to contain the bookmarks you’d like to be listed. This code snippet takes care of this:

<?php
$bookmarks = array();
$bookmarks = get_bookmarks('category=111&orderby=rand');
?>

You can use any of the parameters (found here) to tweak the data you are requesting from the database. In this example above, I’m pulling the links from the category with an ID of 111 and I’m telling the function to display the links in random order.

Step 2 – What’s in the array?

Now, when you’re doing this the first time, you will have no idea of what the content of that array looks like. So to display the content from the array, you’d simply do this:

<?php
$bookmarks = array();
$bookmarks = get_bookmarks('category=111&orderby=rand');

print_r($bookmarks);
?>

When you view your template in WP now, you’ll see a big section of odd-looking data, which looks something like this:

“Array ( [0] => stdClass Object ( [link_id] => 7 [link_url] => http://planet.wordpress.org/ [link_name] => WordPress Planet [link_image] => [link_target] => [link_category] => 0 [link_description] => [link_visible] => Y [link_owner] => 1 [link_rating] => 0 [link_updated] => 0000-00-00 00:00:00 [link_rel] => [link_notes] => [link_rss] => [object_id] => 7 [term_taxonomy_id] => 2 [term_order] => 0 [term_id] => 2 [taxonomy] => link_category [description] => [parent] => 0 [count] => 7 [recently_updated] => 0 )”

This data may seem completely useless at this stage (and functionality-wise it is), but we will reference this output just now when we construct our links list. Just as an example – [link_url] & [link_image] are examples of variables that you can call on for each bookmark that was queried. The above data dump is also only the data associated with one bookmark from the array.

Step 3 – Constructing the platform

So next up, we want to start building the HTML around the list itself – before we code the output of the individual links. Using the same code as above (but removing the code added in Step 2, since this was for reference-use only), we will build it out as follows:

<div id="links" class="widget">
<h3>Kudo's & Respect</h3>
<ul> <?php
$bookmarks = array();
$bookmarks = get_bookmarks('category=111&orderby=rand');
foreach ( $bookmarks as $bookmark ) {
?>

***The link output will be here***</ul>
</div>
<!--widget-->

If you work through that code snippet, you’ll see that we’ve just added the HTML to allow us to style this widget specifically later on. The only new dynamic code that we’ve added is the foreach loop, which will be cycling through the $bookmarks array to display the links.

Step 4 – The Output

Now we need to include the output code for each bookmark. The code for this will be included within the foreach loop – so we only need to include it once, as the foreach loop will cycle through the array and display each link according to our specification.

This is what that code looks like:

<li>
<a title="<?php echo $bookmark->link_name; ?>" href="<?php echo clean_url($bookmark->link_url); ?>" target="_blank">link_name; ?></a>
</li>

Within that code snippet, we’ve used 3 variables (from the data dump we produced in Step 2) to dynamically construct the output of each link. This tutorial assumes that you’re comfortable with the HTML involved here – so I won’t be covering that. But I would like to just define the 3 variables we’ve used:


<ul>
<li>$bookmark->link_url - The external URL of the link</li>
<li>$bookmark->link_name - The name / title of the link</li>
<li>$bookmark->link_image - The image of the link (in this case it'd be the favicon we'd like to display</li>
</ul>

So if you include this code in our global code snippet, you would have the following complete, custom widget function:

<div id="links" class="widget">
<h3>Kudo's & Respect</h3>
<ul>$bookmarks = array();
$bookmarks = get_bookmarks('category=111&orderby=rand');
foreach ( $bookmarks as $bookmark ) {
?>
<li><a title="<?php echo $bookmark->link_name; ?>" href="<?php echo clean_url($bookmark->link_url); ?>" target="_blank"><?php echo $bookmark->link_name; ?></a></li>
</ul>
</div>
<!--widget-->

Step 5 – The Style

The last step is to add some simple styling to align the favicon & link appropriately. Here’s some similar CSS to which I use to construct the “Kudo’s & Respect” widget on my own blog:

#links ul li {
float: left;
display: inline;
margin: 0 20px 0 0;
line-height: 30px;
}

#links ul li a {
color: #000;
text-decoration: none;
font-size: 12px;
line-height: 16px !important;
padding: 1px 0 1px 26px;
}

#links ul li a:hover {
color: #666;
}

Conclusion

As you will see from the above example, it is not overly advanced to create a custom output function using arrays and custom queries in WordPress (the HTML & PHP involved are both only at an intermediate level). Even though most WP users will never find the need to use a custom function like this, it is helpful to those of us that likes to push WP’s boundaries.

Using the exact same method as I’ve used, you can create similar custom functions for categories, pages & posts. The easiest way of determining how to construct one’s own output is by simply dumping the data from your queried array to the screen (as in Step 2 in the example) and using that as a reference point for your output.

WordPress Tip: Add your branding

Ed: This article is part of the 21 Days of WordPress Tips

While I love WordPress and every one of my clients know their site is running on an open source platform, it’s still nice to add your own branding to the back end so the client never forgets who did such a fabulous job building their website.

There ‘s a few things you can do to add your own flavor to an installation of WordPress.

1. Brand the login page

Since the login page is the first thing your client sees before working on their web site, it’s the first place you should start.  Let’s change out the big WordPress logo for one of your own.

The plugin I use is BM Custom Login.

I love this plugin because it comes with a .psd file you can edit to add your logo and company name.  It also has pretty decent instructions on how to make your own image and get it uploaded.

The one issue with this plugin is it’s only tested through v 2.5.1 of WordPress and it’ll take some CSS magic to upgrade it to work with v 2.7.  To see the changes I made, check out my versions of the two CSS files that come with the plugin:

You can see my custom login screen here.

outthink

(plus, for an easy to remember WordPress login URL, check out this tutorial)

2. Add your logo to the header

Another way to add your branding is to change the WordPress logo in the header of the dashboard to your own.

I’ve whipped up this quick little plugin that will allow you to modify both the background color and the logo.  Just change lines #16 and #19.  Feel free to use and modify to your needs!

My Admin Logo (.zip)

adminlogo

3. Add your link/logo to the footer of the site

This is a pretty common approach, however it’s always a good reminder.  Whenever you release a new theme, whether for a client or for public use, be sure to add your logo and link to the footer.php file.  Keep it small and unobtrusive and I’ve never had a client have a problem with it.

 

Those are my three tips to add your own branding to an installation of WordPress.  Enjoy!

WordPress as CMS: How to make custom fields easy to use

Ed: This article is part of the 21 Days of WordPress Tips

The most frustrating feature of WordPress is custom fields. They provide huge potential for usability but remain largely under developed.

The term “custom fields” means nothing to anyone but a WordPress power user and their explanation (“Custom fields can be used to add extra metadata to a post that you can use in your theme.”) is even less helpful.

morefields1

However, they can be very powerful if used correctly.

You can use them any time you want to show content on a specific part of your page. Here’s a few examples:

  • Contact information
  • Embed code for videos, Wufoo forms, etc
  • Links to specific images
  • Product information (model, price, quantity, etc)

By having this content in a specific custom field, it allows you to display and manipulate it apart from the other page content.

The problem is the user interface is absolutely horrid. Any custom field you’ve every used is in a drop down box. Not to mention the text box for holding the data is small. And if you want to add any HTML tags, it again becomes completely useless to the average user.

Thankfully a developer by the name of Henrik Melin also saw this deficiency and wrote a plugin called More Fields.

This plugin takes control of the custom fields and allows you to add any number of new input blocks to the Write/Edit pages in WordPress. The input types include:

  • Text
  • Textarea
  • WYSIWYG
  • Select
  • Radio
  • Checkbox

I’ve already used this plugin for a few clients and it works fantastic. It allows you to add any number of custom fields in a way that makes it extremely easy to update.

Here is a screenshot of a Test Box I created in just a couple minutes that uses a WYSIWYG, radio select and drop down select:

morefields

If you’ve ever wanted to take control of your Write/Edit pages in WordPress and make them much more useful for you or your client, download and install the More Fields plugin immediately!

Now that you’re made some custom fields that are actually useful, how do you use them in your theme development? This will be in Tuesday’s tip, so stay tuned!

WordPress Tip: Template files and naming conventions

Ed: This article is part of the 21 Days of WordPress Tips

The WordPress template files can often be confusing. Figuring out which files get used and when, which ones you don’t need, etc is very daunting. Not to mention, this information is pretty hard to sift through in the WordPress codex.

In this post article I’ll give you a few of my favorite tips when it comes to piecing together the WordPress template files to meet your needs.

753px-template_hierarchyThe Hierarchy

Click the picture on the right to get a look at how the WordPress template hierarchy works. Learning this is a must in developing your own themes.

First off, index.php is the root of everything. You can actually run an entire theme off an index.php and style.css. And if you are missing a template file that is needed, index.php will be defaulted to.

Another heavily used file is archive.php. If you open this file from the “default” theme that downloads with WordPress, you’ll see code that’s used to show all the categories, dates, authors, etc archives.

Bookmark this image and refer back to it any time you get stuck on which template file will be called and when.

Powerful Categories

One of the more powerful template files that I rarely see used is the category-[id].php. The image above is somewhat misleading as the file will never actually be named category-id.php. The ‘id’ part of the filename is replaced with the numeric id for the category you would like to show. i.e. category-1.php or category-28.php to correspond to categories id 1 and 28.

Using these template files can be very useful if you would like to show an entire category of your site in a custom layout.

I use this technique on the SmallBizTrends.com website. I have a default category.php file that shows for any category on the site (here’s an example), however there is a special category that is sponsored by HP that needed to display different elements. I used a category-[id].php template file to split out that section and show those posts differently (click here to see it).

Page Template Filenames

As we’ve seen in earlier WordPress tips, you can create custom page templates that override the default page.php template. Again, the above image is a bit misleading as the file doesn’t have to be named pagename.php. In fact, it can be named whatever you like, however I recommend a very specific naming convention.

When you create a page template it is either for a specific page on your site (i.e. Home Page, About, etc) or a specific layout (i.e. one column, two column, etc). My advice is to include the descriptions in the name of the file:

  • page-home.php
  • page-about.php
  • page-one-column.php

By following this convention, you and anybody else that works on the site in the future will know what those template files do. I’ve seen page template files named all kinds of random things and it’s always hard to sift through exactly what files you need. Follow the above naming convention to save yourself and any future developers a huge headache.

A useful 404

It’s easy to get caught up in creating your WordPress theme and your content and forget that this very useful template file exists. The 404.php gets called when a page is called that doesn’t exist. Whether it’s a broken link or a user typing something wrong, odds are good that somebody is going to a request a page of your site that doesn’t exist. Instead showing a useless 404 error, use this opportunity to point them to other portions of your website.

You can see ours here

wtf4040

That’s my favorite tips on how to correctly use your template files. You have one or two of your own?

WordPress Tip: Common uses for conditional tags

Ed: This article is part of the 21 Days of WordPress Tips

The WordPress core provides several “conditional tags” that are helpful in showing different content or code depending on where you are on the site. You can read about all of them at the WordPress codex, however I’m going to share with you a few I use the most plus a couple things to look out for.

is_page()

In most business websites you’re going to hard code the top navigation as opposed to automatically showing links to all the top level pages. The problem this can cause is when you want to indicate to the user what section of the site they are on. This is where the is_page() conditional tag comes in. You can use it to test whether the user is on the page and then apply a different CSS class to the element. Here’s an example:

<li><a <?php if(is_page(2)) : ?> class="current_page"
<?php endif; ?>href="<?php bloginfo('url'); ?>/about-us/">
About Us</a></li>

As you can see, I’m using is_page(2) to see if the current page has an ID of 2. If it does, I will add a class of “current_page” to the element which will allow me to style it differently.

If you read through the WordPress codex entry on is_page(), you’ll notice I could have also used:

The page’s slug: is_page(‘about-us’)

Or the page’s title: is_page(‘About Us’)

And while this is much easier to use and produces more readable code, if the client ever changes the name of the page then this code will break. I highly recommend using the page ID instead of the slug or title when using is_page().

Tip: Since v2.5 of WordPress, there is no column in the admin panel that shows the page/post ID. In order to quickly see it, hover over the Edit link and look at the post=XXX part of the url. This is the page ID you want to use.

is_home() and is_front_page()

On most sites, the home page has a different display with different elements that the rest of the site. This is where these two conditional tags can be very helpful.

However, there are a couple things to look out for…

At first glance you might assume these two conditional tags do the same thing. Isn’t your home page the same as your front page?

This is not how WordPress views it.

The is_home() conditional tag is left over from the earlier days of WordPress when it was merely a blog platform. As WordPress grew into a full content management system and added the ability to set a static page as your home page (In the admin panel: Settings -> Reading -> Front page display), is_home() no longer did what it’s name implies.

The is_home() conditional tag will only return true on the main blog page of your site.

If you set a static page as your front page, is_home() will return false when viewing your home page.

This is where I recommend you use is_front_page(). It will return true when you are looking at the home page of your site whether it’s set to a static page or your main blog page. It’s more consistent and, therefore, more useful.

is_single()

This is another conditional tag that I use a lot. It returns true whenever you are viewing a single blog post. This is great for showing different sidebar elements such as related posts or author information for each blog post.

in_category()

Another feature that is often requested is to treat a post differently depending on what category it is in.

For instance, maybe you want to show the contact information for the support department on any post addressing support issues. You can use the in_category() conditional tag to do this automatically so you don’t have to remember to type it in every time.

<?php
if(in_category(3)) {
?>
<h4>Contact Support</h4>
1-800-800-8000
support@support.com
<?php
}
?>

There are several other conditional tags available, but these are the ones that you’ll find the most use for.