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.