There’s at least 3 ways to code if conditionals and else statements in WordPress using PHP.
In the first 2 examples below, we’ll use the most common methods using if and else.
In the 3rd method, we’ll use the ternary operator question mark ? and colon :
In programming language, a ternary operator is commonly referred to as a conditional operator which excepts 3 arguments.
Is the use of a ternary operator a more efficient way to code if conditionals and else statements using PHP? Test the code yourself and find out.
Here’s 3 working examples you can paste into your child themes functions file and test at the same time or individually :
if …. else conditional #
The first 2 methods use if else conditional statements.
add_action( 'loop_start', 'else_if_method_one' );
function else_if_method_one() {
if ( is_front_page() ) :
echo 'Only on the front page';
else :
echo 'Otherwise different on all others';
endif;
}
You can also use code like this:
add_action( 'loop_start', 'else_if_method_two' );
function else_if_method_two() {
if ( is_front_page() ) {
echo 'Only on the front page';
} else {
echo 'Otherwise different on all others';
}
}
Ternary Operator #
In the 3rd example, we’ll use a conditional tag with the operator ? and : like this :
add_action( 'loop_start', 'ternary_operator_method_three' );
function ternary_operator_method_three() {
$output = is_front_page() ? 'Only on the front page' : 'Otherwise different on all others';
echo $output;
}
The above method uses the ternary operators ? and : which enable you to change the value of the $output variable.
In this case, if we’re on the front page, the 1st value is true ‘Only on the front page’
Otherwise, if we’re not on the front page, the 1st value is false and the 2nd value is true ‘Otherwise different on all others’.
Note: is_front_page()
assumes your child theme contains a front-page.php file otherwise, in these examples, returns true on the home and blog page ( posts page ) in genesis.
Use With Variables
You can use variables with actions and filters like this:
add_action( 'loop_start', 'ternary_operator_variables' );
function ternary_operator_variables() {
$output = $a ? $b : $c;
echo $output;
}
This code reads, if $a is true, use the value for $b else use the value for $c.
All you need to do is define your variables.
Here’s an example from the genesis featured posts widget:
$title = get_the_title() ? get_the_title() : __( '(no title)', 'genesis' );
An example using printf
printf( genesis_html5() ? '<p class="entry-meta">%s</p>' : '<p class="byline post-info">%s</p>', do_shortcode( $post_info ) );
See here for a working example using the ternary operators with variables.
Was This Tutorial Helpful?