WordPress Code Series If Then Else

We thought it would be good to create a series of posts with examples of code blocks in WordPress, The WordPress code is a mix of PHP HTML and WordPress custom functions.

There are several different ways that the IF statements are used in WordPress, these can be confusing for new developers.

What we want to do is look at real examples in the Twenty Eleven theme, then offer some tips when writing our own statements.

IF THEN ELSE ENDIF

Lets start by looking at this statement in the real world, IF raining THEN raincoat ELSE jacket, so raining becomes the condition on which we make our choices to wear a raincoat or jacket.

We will see several different ways of structuring the IF statements, if we were writing a function in functions.php and we wanted to return our answer from a function.

<?php echo what_to_wear( true ); ?> 

This would return ‘You better get your raincoat’

function what_to_wear ( $is_raining ) {
   if ( $is_raining ) {
      return 'You better get your raincoat';
   } else {
      return 'wearing your jacket is fine';
   }
}

Shorthand Statements

php also has a form of shorthand, here we do not use the words IF THEN ELSE, What to Wear = (raining ? Raincoat : Jacket )

So we can see that the question mark ? is the THEN, the colon : is the ELSE, and the parenthesis are the IF statement, the code below returns ‘Jacket’.

$is_raining = false;
$what_to_wear = ( $is_raining ? 'Raincoat' : 'Jacket' );

HTML and PHP Mixed

In the page templates we see the third structure, these code calls we see inside php tags, notice that the colon : replaces the opening bracket { and the THEN statement, and we are introduced to the endif; which replaces the closing bracket }

<?php if( $is_raining ) : ?>
   <p>It is raining outside better get your Raincoat</p>;
<?php else : ?>
   <p>It is not raining outside you can wear your Jacket</p>;
<?php endif; ?>

ELSEIF

Ok so lets add a new condition and the ‘is equal to’ operator == based on the weather what shoes should we wear?

function what_shoes_to_wear ( $the_weather ) {
   if ( $the_weather == 'raining' ) {
      return 'Wellingtons or galoshes';
   } elseif ( $the_weather == 'sunny' ) {
      return 'Sandals or flip flops';
   } else {
      return 'Sensible Footwear';
   }
}

Writing Code

In the WordPress forums we see no end of topics where a syntax error has locked out the topic starter, the most common is failing to close a block or line of code > } or ;

To avoid this we study code structures, look at the starting and closing blocks, indent the code and always use a good syntax editor like Notepad++

Notepad Plus Plus Screenshot

NotePad++ is a free syntax editor, so there are no excuses for using Notepad.

Notice the different colors for the text, and the block highlighting, if we select an opening brace { or paranthesis ( the closing element is then highlighted in red, a pretty cool editor and at no cost.

If we are writing a new code block, we will always start with a nested block structure like this before we add the code.

function what_shoes_to_wear ( $the_weather ) {
   if ( ) {
      return '';
   } elseif ( ) {
      return '';
   } else {
      return '';
   }
}

Real Twenty Eleven Code Examples

Lets start with a simple if statement with no braces, in the twenty ten functions.php file, these lines are looking to see if the $content_width variable has been set,  note: (! is the operator not ).

If the $content_width variable is not set then the code sets it to 584, notice the statement is terminated with a semi-colon ;

if ( ! isset( $content_width ) )
   $content_width = 584;

Another statement can be found inside a function, here WordPress uses the braces for this statement, we can find this code in the function twentyeleven_body_classes() at the end of the functions.php file.

is_multi_author() is a WordPress function call that returns true or false, the code takes the return and if it is again false (not operator !) sets a ‘single-author’ class to the body.

if ( ! is_multi_author() ) {
   $classes[] = 'single-author';
}

Shortcode Example

Next we look for a shortcode example, for this we have to look in the /inc/ folder in the widget.php file, at the end of this file we find these two lines.

The widget code requires a value for the $title and $number, look the the $title if the admin has entered a title then return the instance title else it will return an empty string.

$number requires an integer value, if the admin had entered ‘fred’ in the “Number of Posts” then the function will return the default 10 instead, this value is used in a WP_Query() to return the posts.

$title = isset( $instance['title']) ? esc_attr( $instance['title'] ) : '';
$number = isset( $instance['number'] ) ? absint( $instance['number'] ) : 10;

Mixed PHP and HTML

Last we open the page.php file and look for an example where we have HTML and PHP mixed in the same file, this example is for the WordPress Sticky Post, switching the title to H2 instead of H1.

<?php if ( is_sticky() ) : ?>
   <hgroup>
      <h2><a href="<?php the_permalink(); ?>" title="<?php printf( esc_attr__( 'Permalink to %s', 'twentyeleven' ), the_title_attribute( 'echo=0' ) ); ?>" rel="bookmark"><?php the_title(); ?></a></h2>
      <h3><?php _e( 'Featured', 'twentyeleven' ); ?></h3>
   </hgroup>
<?php else : ?>
   <h1><a href="<?php the_permalink(); ?>" title="<?php printf( esc_attr__( 'Permalink to %s', 'twentyeleven' ), the_title_attribute( 'echo=0' ) ); ?>" rel="bookmark"><?php the_title(); ?></a></h1>
<?php endif; ?>

We hope that these posts give an insight and some pointers to new WordPress theme developers.

It is nice to hit the ground running ripping and into some code, but a good understanding of the basic logical code structures are key to success.

Once we have the grasp of these functions they will transport between other code languages, with a different syntax, in VB it would be IF THEN ENDIF;

Notices

We do require your feedback to improve our themes and tutorials, please leave your comments good or bad.

Code disclaimer information

If this document contains programming examples, www.DigitalRaindrops.net grants you a nonexclusive copyright license to use all programming code from which you can generate similar functions tailored to your own specific needs.

All sample code is provided by http://DigitalRaindrops.net for learning illustrative purposes only.

These examples have not been thoroughly tested under all conditions. www.DigitalRaindrops.net, therefore, cannot guarantee or imply reliability, serviceability, or function of these examples.

All programs contained herein are provided to you “AS IS” without any warranties of any kind. The implied warranties of non-infringement, merchantability and fitness for a particular purpose are expressly disclaimed.

Membership

Registration and Membership is no longer required for downloading files or interacting with Digital Raindrops, posting a comment or topic in the forum does use Captcha to reduce spammers.

This website is a tool to support and promote WordPress and Artisteer theme development, please support, share and give credit for any benefits you gain from the tutorials on this website.

2 thoughts on “WordPress Code Series If Then Else

  1. We are working on a book site and wanted to see if you could help us with this statement. We have the code working to show title text if there is a colon in the title, but need it to just show the title if there is no colon.

Leave a Reply

Connections

Connect with Us
Follow Digital Raindrops on Twitter Join Digital Raindrops on Facebook
Share

Related Posts