0

What I'm trying to do is add a fallback image to this shortcode function that grabs the featured image to account for the possibility that a post has no featured image. (This function creates a shortcode because I need to use that within another plugin that requires the shortcode to generate HTML display.)

I've read the related questions and none deal with a shortcode or the fact that I need to return only the image URL.

This works and returns the URL of the featured image:

add_action( 'init', 'register_featured_image_shortcode');

function register_featured_image_shortcode(){
add_shortcode('my_get_thumbsrc', 'my_get_thumbsrc');
}

function my_get_thumbsrc($id) {
global $post;
$id = ($id) ? $id : $post->ID;

if ( has_post_thumbnail($id)) {

$image_url = wp_get_attachment_image_src( get_post_thumbnail_id($id), 'inthenews-thumbnail');

return $image_url[0]; // return just the url

}
}

This doesn't work; I get an empty <img src field in page source:

add_action( 'init', 'register_featured_image_shortcode');

function register_featured_image_shortcode(){
add_shortcode('my_get_thumbsrc', 'my_get_thumbsrc');
}

function my_get_thumbsrc($id) {
global $post;
$id = ($id) ? $id : $post->ID;

if ( has_post_thumbnail($id)) {

$image_url = wp_get_attachment_image_src( get_post_thumbnail_id($id), 'inthenews-thumbnail');

return $image_url[0]; // return just the url
}
else  {
    return get_stylesheet_directory_uri() .' /white-placeholder-200x100.png';
}
}

So how to I add the fallback image white-placeholder-200x100.png with an else construct? Is return the wrong way to provide the URL? echo doesn't work.

1

First, you have a typo in the provided code: an extra space between the apostrophe and the forward slash before "white-placeholder."

Second, without examining the underlying logic in detail, I might try for the else statement:

else {

$placeholder_image = get_stylesheet_directory_uri() . '/white-placeholder-200x100.png';

return $placeholder_image;

}
  • Ha, I'm sure I tried returning a variable, i.e. , $placeholder_image, but I guess not. Works fine, thanks. – markratledge Sep 16 '15 at 15:03
  • My pleasure - and thanks for marking my answer satisfactory, and boosting me over the magic 50 rep mark! I have only 6,160 or so points to catch up to you, as of this writing, so consider me hot on your heels. – CK MacLeod Sep 16 '15 at 18:21

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.