Conditional logic in WordPress

Sometimes we need to use conditions in the code.
Here are some conditional examples using the now expired Beans WordPress Framework. Here is a link to my Beans tutorial website. (Not sure how long the site will stay online.)

add_filter( 'beans_layout', 'example_force_layout' );
  function example_force_layout() {
    if ( is_front_page() ) {
      return 'c'; // Full width content
    }
    if ( is_page(contact) ) {
      return 'c_sp'; // Content left - sidebar right
    }
    else {
      return 'sp_c'; // Sidebar left - content right
   }
 }
/***** My modifications - This is just part of a code *****/
// Set default image for front page. 
   if ( is_front_page() ) {
      $image_url = 'https://beans-tests.dev.cc/wp-content/uploads/
Blue-pattern-cool-bg.jpg';
   }
// Set default image for contact.
   if ( is_page('contact') ) {
      $image_url = 'https://beans-tests.dev.cc/wp-content/uploads/
Green-mountains.jpg';
   }
// Set a default image if no feature image is found. 
   if ( false === $image_url ) {
     $image_url = 'https://beans-tests.dev.cc/wp-content/uploads/
1402533.jpg';
  }
// Stop here if we are on a single view.
if ( is_singular() || is_admin() ) {
return $content;
}

// Return the excerpt() if it exists other truncate.
if ( has_excerpt() )
    $content = '<p>' . get_the_excerpt() . '</p>';
else
    $content = '<p>' . wp_trim_words( get_the_content(), 40, '...' ) . 
'</p>';


There are some variations of the above code. 
Switch out is_singular() || is_admin() with !is_archive()
// Only apply to non singular view.
if ( !is_singular() ) {
if ( is_singular() && is_page() ) {
     remove_all_actions( 'beans_post_header' );
  }
if ( is_single() or is_page() ) { 
beans_remove_action( 'beans_post_image' );
}

Additional resources:
Developer WordPress.org themes
Codecademy PHP
PHP Net Manual

Share the article:

Leave a Reply

Your email address will not be published. Required fields are marked *