GuyWeb

WordPress conditional statements for simpletons

August 22nd, 2008

I’m a PHP thickie to be honest. I blunder around attempting to understand what I’m doing with programming but rarely have a clue. It’s all just magic fairy dust to me. When I get something working, frankly I’m amazed. Today I conquered WordPress conditionals. I thought I’d log down what I did because I’m likely to need this knowledge again in the future. If it helps out others along the way, great.

The challenge

When creating a WordPress theme you can use a number of individual template files to control different types of content. However, very little often changes from page to page. You end up retyping the same code into each template. When you want to make a change to your theme you have to go and edit the code numerous times across different templates. A better solution would be to have a few template files as possible and apply a different output based on certain conditions. WordPress offers us conditional tags to do this very thing.

Imagine my scenario. I have blog posts published in full on the front-page of my site. Each of these posts contains a link in the title which takes us to the full, permalinked article plus comments. I can use the same WordPress loop for the homepage as for the single articles save for a two things: 1. The link in the title isn’t needed on the single post as it would self-link. 2. The link to the comments isn’t needed for the same reason.

The solution

<?php if (is_single()) { ?>
<?php the_title(); ?>
<?php } else { ?>
<a class="bookmark" href="<?php the_permalink() ?>"
rel="bookmark" title="Permanent Link to <?php the_title(); ?> ">
<?php the_title(); ?> </a>
<?php } ?>

The code above illustrates the syntax to use. The emboldened bits provide the conditional logic and the bits between are the code I want to output. And there you have it. Simple really.

Tags: ,