1

I am using this code for search results display:

    $image = wp_get_attachment_image_src( get_post_thumbnail_id(), 'thumbnail' );
    $my_image = ( $image[0] != '' ) ? ' <img alt="' . esc_attr( sprintf( the_title_attribute( 'echo=0' ) ) ) . '" title="' . esc_attr( sprintf( the_title_attribute( 'echo=0' ) ) ) . '" class="tagim" src="' . $image[0] . '"/>' : '';

This works fine but I am getting PHP Notice: Undefined variable: output if the post does not have a featured image.

In this case what would be the best way to point to a default placeholder image for the "src" in variable $my_image

1

You'd want to put the <img/> tag and all the necessary content for the default image after the final colon in the following line:

$my_image = ( $image[0] != '' ) ? ' <img alt="' . esc_attr( sprintf( the_title_attribute( 'echo=0' ) ) ) . '" title="' . esc_attr( sprintf( the_title_attribute( 'echo=0' ) ) ) . '" class="tagim" src="' . $image[0] . '"/>' : '';

What that line does is say that if the $image[0] variable is not equal to blank ($image[0] != ''), then use the following, and it then supplies the image tag, the title, the alt and src. Then the segment after the colon is basically the else. So if NOT BLANK do this ELSE do this. What you've got as an else is basically nothing.

So try this, where we're adding something to the ELSE portion:

$my_image = ( $image[0] != '' ) ? ' <img alt="' . esc_attr( sprintf( the_title_attribute( 'echo=0' ) ) ) . '" title="' . esc_attr( sprintf( the_title_attribute( 'echo=0' ) ) ) . '" class="tagim" src="' . $image[0] . '"/>' : ' <img alt="' . esc_attr( sprintf( the_title_attribute( 'echo=0' ) ) ) . '" title="' . esc_attr( sprintf( the_title_attribute( 'echo=0' ) ) ) . '" class="tagim" src="theurlforyourdefaultimage.com/imagename.png"/>';

You'll need to provide the URL to your default image. Not sure if it's in a folder in your theme, or something you've uploaded, but for the time being you can just use the full URL to test.

I guess also determine if you still want the same alt and title even if there's a default instead of a featured image or if you want them to also be something generic.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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