<?php if ( ) { ?> <?php } else ( ) { ?> <?php } ?>
Conditional Tags:
- is_page()
- is_single()
- is_category()
- is_author()
- is_home()
Usage Examples:
- is_page(‘3’)
- is_page(‘About Us’’)
- is_page(‘about-us’)
- is_category(‘5’)
- is_category(‘Apples’)
- is_category(‘apples’)
Example #1: Multiple conditions
<?php if ( is_page('Apples') ) { ?> <img src="apples.gif" /> <?php } elseif ( is_page('Oranges') ) { ?> <p>This is my text.</p> <?php } else { ?> <?php } ?>
Example #2: This OR That
<?php if ( is_single('Apples') || is_category('Vegetables') ) { ?> <p>This is my text.</p> <?php } else { ?> <?php } ?>
Example #3: Apply the same condition to many things
<?php if ( is_page(array('Apples','Oranges')) ) { ?> <p>This is my text.</p> <?php } else { ?> <?php } ?>
Example #4: Using variables
Variables are another way of calling information from the WordPress database. Often used in plugins and in your WordPress loop, you can also use them within conditional statements.
Let’s say that you want to display in the sidebar a list of links to the sub-pages of a particular parent page, and you want that list to also appear on the parent page as well. What would your conditional statement look like?
<?php if ( is_page('Fruits') && $post->post_parent=="Fruits" ) { ?> <ul> <li>List item</li> </ul> <?php } else { ?> <?php } ?>
In this case, we’re using the $post->post_parent variable to say that we’re applying the condition to all the sub-pages of the “Fruits” page, as well as the actual parent page itself, which we’ve identified with the other condition.
Example #5: “Is Not” Conditions
Continuing with our use of variables, let’s say that you want to display an image at the top of all pages that have the “Fruits” page as their parent page EXCEPT FOR the page about bananas. What would this look like?
<?php if ( $post->post_parent=="Fruits" && !( is_page('Bananas') ) ) { ?> <img src="fruits.gif" /> <?php } else { ?> <?php } ?>
Here, we’re using the “&& !” to say AND EXCLUDE the page about bananas from the condition that we’re applying to every other sub-page.
<?php if (!is_home()) { ?> <img src="source" alt="The image that I want visible everywhere but home" /> <?php } ?>
Sources: