Ever become brave enough to look inside of a WordPress php file? Specifically, a php file from a theme? If you have, you may have noticed that they are filled with If, Then, and Else statements. If you have no idea what these mean, this post is for you.
Php has always been a pain for me to understand, but if you think about it in a logical manner, it begins to make sense. If, then and else statements are used as a means of making decisions, similar to the way you and I make decisions in the real world. Here is an example of how this logic works in WordPress.
< ?php if (have_posts()) : ?>
The if statement within that php function is asking if there are posts. If the blog has posts, WordPress begins processing what is known as “The Loop“.
<? php while (have_posts()) : the_post(); ?>
This piece of code tells WordPress to grab the posts from the MySQL database and display them on your blog. The loop then closes with this function.
<?php endwhile; ?>
If the answer to the if question turns out to be no, WordPress bypasses the loop and displays a message that no posts exist. This is where the else statement comes into play.
< h2 class=”center”>Not Found< /h2>
< p class=”center”>Sorry, but you are looking for something that isn’t here.< /p>
< ?php include (TEMPLATEPATH . “/searchform.php”); ?>
< ?php endif; ?>
That last line of code is the if statement and concludes the function.
If, then, and else are easy to remember when you think of how you function on a daily basis. A real world example, (If I am hungry, Then I’ll eat some food, or Else I’ll starve). Maybe not the best example in the world, but you should be able to get the picture.
I’m no coder by any means but when I read explanations about statements and functions inside of WordPress via Lisa Sabin Wilson’s WordPress For Dummies, it’s as if light bulbs turn on inside of my head. One of those “Ohhhh, so thats what that does” sort of moments.
Be sure to let me know if this post was of any help to you.