PHP for WordPress: Mastering Conditional Statements and Tags
basix

PHP for WordPress: Mastering Conditional Statements and Tags

Tutorial Details
  • Program: WordPress
  • Estimated Completion Time: 15-20 minutes
  • Difficulty: Beginner – Intermediate (Should have working knowledge of HTML, CSS and PHP).

The conditional statements feature is an extremely useful and powerful feature in WordPress; still it remains unused in the development process. You can achieve many things by the simple and smart use of these statements. Sometimes when you need specific text or a unique image to appear on a specific page and not on any other pages in your site, by using conditional statements along with WordPress conditional tags you can achieve this easily without creating multiple pages or templates.


What are Conditional Statements?

PHP “If” statements are generally known as conditional statements. These statements are used within WordPress Theme files along with certain WordPresss functions defining the logic to inform the WordPress database what and how the content should be displayed based on a given criteria. These statements are very important in defining WordPress themes and are similar to creating template hierarchy.

Basic Conditional Statements look like this:

<?php if ( ) { ?>......<?php  } ?>

In layman’s terms, this is pretty simple:

If “something” exists/happens/etc., Do something.

You can (and probably will) use this type of general “if” statement inside WordPress all the time. WordPress has it’s own set of conditional statements as well though, so let’s take a peek at what those look like:


A List of Important WordPress Conditional Tags

Different types of Conditional Tags exist within Conditional Statements. These tags fetch particular information from the WordPress database. These conditional tags are defined for many different items in WordPress e.g. posts, tags, texts, images, categories etc.

Some of the most popular ones are-

1.is_page() - If you want to apply a certain condition to one of your specific page, e.g.  “Contact Us” page. You can use this tag to refer to that page using its database ID number or title or slug/name. For instance:

is_page(’2')
or
is_page(‘Contact”)

2. is_category() – If you want to apply a certain condition to a specific category page e.g. Books, then this tag can be used to refer to that page using its database ID number or title or slug/name. For instance:

 is_category(“4”) 

3. is_home() – This is used to refer to your home page.

4. is_single() – This is used for single page blogs, single posts or attachments.

5. is_tag() – This is used to refer to a tag archive page. It works similar to category page.

6..is_archive() – This is used to refer to archived pages.

7. is_search() – This is used to refer to search results pages.

8. is_404() – This is used to refer to a HTTP 404: Not Found error page.

9. is_author() – This is used to refer to an author archived page.

10. is_comments_popup() – This is used to refer to a comment popup window.

You can get the complete list of tags on the WordPress Codex page.


Learning by Example

This is all fine and well in theory, but let’s dig into some practical code examples of these conditional statements in action.

Example #1:

What should be the code to display an image on your first page, nothing on the second and some text on the third page? (These pages are hypothetical, you can replace them with your own page names, like Contact Us, About, Information, etc…)

  <?php  if ( is_page('First_Page') ) { ?>
<img src="image.gif" />
<?php } elseif ( is_page('Third_Page') ) { ?>
<p>Here is some text….</p>
<?php } else { ?>
<?php } ?>

Please Note-

These codes should be written in your writable theme editor on the page.php file where you want the conditional content to appear.

Extra Note: This is a multi-conditional statement (see the multiple “if, elseif, else…” running logic?) This code checks for the appropriate page using the tags and then displays the items accordingly. You can use unlimited conditions within a code.

is_page(array(‘First_Page’,’Second_Page’)) can be used to display something on both the pages.


Example #2:

How to display a text on either a single post OR a particular category page?

Here you need to use the “||” symbol to display something if any one of the given condition is met. If no condition is satisfied, it displays nothing.

  <?php  if(is_category(Category_Page) ) || ( is_single(Single_Page))  { ?>
  <p>Display  this text….</p>
  <?php  } else { ?>
  <?php  } ?>
  

Extra Note: We used the “||” here, which checks for any of the conditions… Alternatively, we could use the “&&” to create an AND condition, in which both the condition must be met in order to display the item. The “!” is used for excluding something from the list.

E.g. !( is_page(Excluded_PageName)). You can also use variables to refer to the sub pages of a parent page. E.g. post->post_parent=="Parent_Page_Name"


Example #3:

How to load other items like CSS files, Java Script files in one of my pages?

This code snippet will show you how to display contact form files only on your Contact Us page.

  <?php  if ( is_page( 'contact_us_page' ) ) {   ?>
  <link  rel='stylesheet' href='/contactusform.css' type='text/css' media='all' />
  <script  type='text/javascript' src=k'/jqueryform.js'></script>
  <script  type='text/javascript' src='/spec_forms.js'></script>
  <?php  } ?>

Example #4:

How to use conditional tags in your custom post types?

The mixture of custom post types and conditional tags makes a smart way to display information to the users. The following code snippet will enable you to display contact information at the end of your review posts.

  
  <?php  if ( review_entry' == get_post_type() ) { ?>
  <div  id="reviewcontact">
  <p>If  you're impressed by the  reviews, kindly  contact us asap. Give us a call or <a href="/contact"  title="Contact Us">CLICK HERE</a> to send us a message!</p>
  </div>
  <?php  } ?>

Example #5:

How to check if a “post thumbnail” image has been uploaded or not?

The following code checks for an image and display another if not found.

  <?php  if(posted_thumbnail()) {
  show_thumbnail();
  }  else {?>
  <img src="<?php  bloginfo('template_directory');?>/images/default_Image.gif" alt="Image not Displayed">
  <?php  }?>

Conclusion

Thus by mastering these little conditional tags and mixing them with php conditional statements, you can write less and do more in your WordPress site. This not only helps you during the maintenance of your site but it also helps to take advantage of the highly useful WordPress database architecture.

If you guys want to see more of these “basic PHP” tutorials for WordPress, let us know in the comments!

Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://brocknunn.com Brock Nunn

    Awesome post, I am still working through it, but that you so much for addressing this subject matter.

  • http://joelturnergraphics.com Joel Turner

    Great post! I would definitely be interested in more PHP posts. Thanks!

  • Adrian Rice

    Since you asked -

    This guy wants to see more of these “basic PHP” tutorials for WordPress.

    It’s so well written that even a dullard such as myself can understand it.

  • http://wpthemepower.com Zeeshan

    There’s something to learn for every wordpress developer on wptuts+. I knew somewhat about conditional statements, yet never thought of loading custom css and javascript files. Example #3 opened up my mind a little. Thanks.

  • Shawn

    Great tutorial. I’ve read through conditional code before and always got a little hung up on the PHP symbols. Probably pretty basic PHP for many programmers, but great for us wanting to learn just that – the basics. Yes, would love to see more of these basic PHP tutorials.

  • http://www.akkis.gr Akkis

    Thank you! this is really a great tut.

  • http://www.desiredsoft.co.in online php training

    Desired Software Solution Provides PHP Training Bhopal, SEO Training and ASP.NET Industrial Training for MCA and BE Students in Bhopal. Get SEO Training, Major and Minor Project Training for PHP and ASP.NET in Bhopal. We offer cutting-edge learning solutions to everyone who is interested to shape up their career.

  • Fx

    Thanks for this awesome post, always a great way to learn, i’m ready for more basic php for WordPress

  • http://titan-creative.net S3bY

    Great article..conditional tags are the key for making outstanding themes!

  • http://www.themanagementskills.scom Rashid Rupani

    Learning never stops. Nice Article, In-fact very useful

  • http://oddnetwork.org haliphax

    Example #2′s first if statement line should look like this:

    if(is_category(Category_Page) || is_single(Single_Page)) {

    The way it is presented in the article will produce a syntax error.

    • Brandon Jones

      Thanks Haliphax – I just updated it :)

  • http://www.damiencarbery.com Damien

    Is Example #5 pseudo code?
    posted_thumbnail() should be has_post_thumbnail()
    and show_thumbnail() should be the_post_thumbnail()

    <img src="/images/default_Image.gif” alt=”Image not Displayed”>

    • http://www.damiencarbery.com Damien

      Fixing the changed code:

      <?php if(posted_thumbnail()) {
      show_thumbnail();
      } else {?>
      <img src=”<?php bloginfo(‘template_directory’);?>/images/default_Image.gif” alt=”Image not Displayed”>
      <?php }?>

      • http://www.tammyhartdesigns.com Tammy Hart

        +1 on this.

        • http://jkudish.com Joachim Kudish

          +2 the code in the OP is wrong (at least it’s not proper WP functions)

  • Dawn

    Wow, not as scary as I thought, thanks!

  • Antonio Romero

    Hello,

    in many places (like in while have_posts : the_post) we can see the if structure with “:” and “?” but really don’t know if there any advantage of using it.

    Could you please give your thoughts on this? And how would the tags be with the “:”?

    Thanks!

  • Jonathan

    Example 3 is terrible practice. What should be done instead is to move the code out to functions.php, then conditionally enqueue. As an example it is fine, but it is not the correct way to conditionally load styles and scripts with wordpress. I’ve included an example below of how I usually do it, though it’s certainly not the only way.

    function my_style_holder() {
    wp_register_style( ‘homepage’, get_bloginfo( ‘template_directory’ ).’/css/homepage.css’ );
    wp_register_style( ‘archives’, get_bloginfo( ‘template_directory’ ).’/css/archives.css’ );
    if( is_front_page() ) {
    wp_enqueue_style( ‘homepage’ );
    }
    if( is_archive() ) {
    wp_enqueue_style( ‘archives’ );
    }
    }
    function my_script_holder() {
    wp_register_script( ‘scroll-to-top’, get_bloginfo( ‘template_directory’ ).’/js/scroll-to-top.js’, array( ‘jquery’ ), ’1.3′ );
    wp_enqueue_script(‘scroll-to-top’);
    }
    add_action(‘wp_enqueue_scripts’, ‘my_script_holder’);
    add_action(‘wp_print_styles’, ‘my_style_holder’);

    Not only does this method centralize your CSS/JS (and compactly no less), but it also clears up so much of the clutter that conditional stylesheets can create when dealing with large numbers of different page types. I’ve seen no performance hit (though I have not actually benchmarked it, just checked out of curiosity) between the two methods, YMMV.

    • http://www.nomad-one.com nomadone

      HI Jonathan, you’re absolurtely right when you say including scripts the way it was mentioned above is not best practice. The reality is though that the level of developer which this kind of tutorial targets is someone generally still coming to grips with basics.

      Your chunk of code discussing the best practice method of including scripts is something generally beyond someone coming to grips with these basics.

      Of course learning best practices from the beginning would be ideal, but grasping each level first is also important to ensure that the learner understands the concepts required at their specific level of learning.

  • Pingback: wp-coder.net » Theme.fm Weekly Roundup #12 (11/11/11)

  • http://twitter.com/drale2k Drazen Mokic

    When i saw the posts thumbnail i thought it says “PHP 4″ and was a bit shocked :O

  • carlos

    I trying to use conditionals with this code below but I don´t have success. I want to show de custom post if It exists. How can I do this?

    <a href="ID, ‘manual em pdf’, true);
    echo wp_get_attachment_url($download);
    ?>” target=”_blank”>Manual

  • http://www.jqueryrain.com Sanchit

    Very useful article.I would like to see more article of these types

  • http://ar-web.net Khalid

    nice tutorial , please more of this amazing php – wordpress tutorials :)
    Thanks Very Much !! ;)

  • http://www.jeronimonunez.com.ar Jero

    Excellent! Great article! I learn a lot with this posts.

  • http://www.findw3.com findw3

    nice post… thanks

  • Pingback: WordPress Theme Development Training Wheels - Lesson 3 | Wptuts+

  • Pingback: WordPress Theme Development Training Wheels: Day Three | How to Web

  • LauraH

    Exactly what I’ve been looking for! Thanks so much.

  • Pingback: WordPress and PHP | Learning from Lorelle

  • http://switched-on-sites.com MelanieL

    Thanks very much for this article. I was looking for some direction in this area with PHP for WordPress and its been a big help!

    • http://switched-on-sites.com MelanieL

      Using what I’ve learned here, I’m working on the following to make sure I can pull the featured image on both a page and a post and use it as the header for that particular page or post. Anyone have any suggestions?

      ID) ){
      $thumbnail_id = get_post_thumbnail_id($id);
      $thumbnail_img = wp_get_attachment_image_src( $thumbnail_id,

      array(970,225));
      $image = $thumbnail_img[0];
      } elseif (is_page()){
      if (has_post_thumbnail( $post->ID) ){
      $thumbnail_id = get_post_thumbnail_id($id);
      $thumbnail_img = wp_get_attachment_image_src( $thumbnail_id,

      array(970,225));
      $image = $thumbnail_img[0];
      } else {
      $image = get_header_image();
      };
      } else {
      $image = get_header_image();
      };
      else {
      $image = get_header_image();
      };
      } else {
      $image = get_header_image();
      };
      ?>

      • MelanieL

        For some reason, the beginning of my code got cut off. Here it is:

        ID) ){

  • MelanieL

    It still got cut off. trying it here without wrap

    if (is_page()){
    if (has_post_thumbnail( $post->ID) ){

  • http://www.greenleaf-net-solutions.com/ Colin Crawford

    Yes, I want more basic php tutorials for WordPress….

  • http://seozeta.com/ Gerard

    Hi! I had to make a code for show a text.

    Into a: “if is category && $paged < 2" (bla bla…) →

    If have posts and category description, show me the text.
    Elseif have posts and subcategories, show me the text.
    Else, nothing.

    <?php $this_category = get_category( get_query_var( 'cat' ), false );
    if (have_posts() && (category_description())){
    echo "Recent articles on “; single_cat_title(); echo “”;}
    elseif (have_posts() && get_category_children( $this_category->cat_ID ) != “”) {
    echo “Recent articles on “; single_cat_title(); echo “”;}
    else {} ?>

    Why I did that? Because I’m using a SILO system in my WordPress, so I don’t want to display a post of a subcategory into a category parent. Moreover, my theme shows a list of subcategories in the category parent. The category description and the subcategories list are located between the title and the loop, so it’d be nice to put a text at the beginning of the loop only if have posts. So this code shows a text saying “Recent articles on (category)”, if there are posts, and there are category description OR subcategories list. Is it right?

    In fact, the get_category_children function is deprecated, but it’s still working.

    Thanks.

  • Hakko

    I tried your code, but it won’t work for me..
    I’m trying to show social share links based on the page showed. For testing i’m just using text. I created a shortcode (using the shortcoder plugin) which contains this code:

    page 36

    page 24

    other page

    I enter this shortcode in the sharebar plugin, and then all it does is just show everything like this (while i’m on page 36):

    page 36
    page 24
    other page

    anyone care to share his thoughts?

  • Pingback: Memasang Tombol Previous Next Post Dengan Gambar | Majuterus