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
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.
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.An alternative would be to use a ternary operation instead of a
if/else
. It’s up to personal preference.