0

i have this basic while loop for my posts

<?php

         if ( have_posts() ) : while ( have_posts() ) : the_post();

         $title = get_the_title();

         $article = apply_filters( 'the_content', get_the_content() );

         $date = get_the_date();

         $source = get_post_meta( get_the_ID(), '_articles_url', true );

         $img = wp_get_attachment_image( get_post_meta( get_the_ID(), '_articles_image_id', 1 ), 'full', 1, get_post_meta($attachment_id, '_wp_attachment_image_alt', true) );


    ?>

i want to write a conditional to check if $img has a value or not , and to load a static default image in case of $img is empty.

1 Answer 1

0

According to the get_post_meta() function reference in the WordPress Codex, "If there is nothing to return the function will return an empty array unless $single has been set to true, in which case an empty string is returned."

That means we can use ternary operators to check whether get_post_meta() returns an empty string, and if so then we assign the static image instead. We'll only need to modify the line where the $img variable is defined:

$img = 
  ( '' == get_post_meta($attachment_id, '_wp_attachment_image_alt', true) )
  ?
  get_template_directory_uri() . '/images/default-img.png' // updated example per comment
  :
  wp_get_attachment_image( get_post_meta( get_the_ID(), '_articles_image_id', 1 ), 'full', 1, get_post_meta($attachment_id, '_wp_attachment_image_alt', true) )
  ;
3
  • this is great , very useful operator . but i'm still facing one more problem which is adding the static image reference the src of the image should have ( echo get_template_directory_uri(); ?>images/default-img.png ) when i inspect the img element it is putting the whole code as a src insted of processing it , not really sure what i am doing wrong Commented Feb 25, 2015 at 20:06
  • At this point, you're not trying to echo text to the browser -- you're trying to set the value of a variable. You need to append /images/default-img.png as a string to the end of what's returned by get_template_directory_uri() (the function doesn't put a forward slash at the end, so you need that at the beginning of whatever you're appending to it) and assign that full value to the $img variable. So here's how that line would look: ? get_template_directory_uri() . '/images/default-img.png' : Commented Feb 25, 2015 at 21:05
  • yeah i was trying to concat strings with get_template_directory_uri() but was getting syntax errors but i got it figured out now '<img ' . 'src="' . get_template_directory_uri() . '/images/default-img.png"' . '>' thanks alot for your help . Commented Feb 25, 2015 at 21:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.