skip to Main Content

I’m still new to PHP and wrote this if-else statement and it’s working but I am not confident enough to put it online on my blog:

  • If it’s the homepage, show logo.png
  • If it’s not the homepage & if there’s a thumbnail, show the thumbnail.
  • If it’s not the homepage & there’s no thumbnail, show the logo.

Is my code correct and optimal?

<?php if(is_home() || is_front_page()){ ?>
      <meta property="og:image" content="<?php echo get_template_directory_uri(); ?>/images/logo.png">
      <?php } else if (!is_home() || !is_front_page()){ ?>
      <?php if( !empty(get_the_post_thumbnail()) ) { ?>
        <meta property="og:image" content="<?php echo get_the_post_thumbnail_url(get_the_ID(), 'medium_large'); ?>" />
        <?php } else { ?>
        <meta property="og:image" content="<?php echo get_template_directory_uri(); ?>/images/logo.png">
      <?php } ?>
    <?php } ?>

2

Answers


  1. Your code will work fine, as a good practice we must keep the word optimization in mind, if we think the same here the else if is not required we can write the same inside the else.

     <?php if (is_home() || is_front_page()) { ?>
            <meta property="og:image" content="<?php echo get_template_directory_uri(); ?>/images/logo.png">
        <?php } else { ?>
            <?php if (!empty(get_the_post_thumbnail())) { ?>
                <meta property="og:image" content="<?php echo get_the_post_thumbnail_url(get_the_ID(), 'medium_large'); ?>" />
            <?php } else { ?>
                <meta property="og:image" content="<?php echo get_template_directory_uri(); ?>/images/logo.png">
            <?php } ?>
        <?php } ?>
    
    Login or Signup to reply.
  2. Since it’s only two different values you’re switching between, you can do it in one single if/else.

    I also added the value to a PHP variable instead of duplicating the HTML code inside the if/else‘s. Imo, it helps with both readability and maintainability.

    <?php
    $isHomeOrFront = is_home() || is_front_page();
    
    if (!$isHomeOrFront && !empty(get_the_post_thumbnail())) {
        $ogImage = get_the_post_thumbnail_url(get_the_ID(), 'medium_large');
    } else {
        $ogImage = get_template_directory_uri() . '/images/logo.png';
    }
    ?>
    
    <meta property="og:image" content="<?= $ogImage ?>">
    

    An alternative would be to use a ternary operation instead of a if/else. It’s up to personal preference.

    $ogImage = (!$isHomeOrFront && !empty(get_the_post_thumbnail()))
        ? get_the_post_thumbnail_url(get_the_ID(), 'medium_large')
        : get_template_directory_uri() . '/images/logo.png';
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search