Get a post’s thumbnail url or display default image in shortcode

I checked it out further and there were a couple of problems with your code.

  • your if statement checks for a post ID, but you don’t have a check for whether or not there is actually a featured image set, so I added a condition to the if statement
  • your closing bracket for get_post_thumbnail_id() was misplaced
  • you were not actually echoing $thumb_url
  • wp_get_attachment_url() returns the image src (not an array) and does not take any additional parameters beyond the attachment ID, which meant that $thumb_url[0] was returning just the first letter of the image src. Looks like you meant to use wp_get_attachment_image_src() which takes an image size parameter. (See codex: Function Reference/wp get attachment url, Function Reference/wp get attachment image src)

Here my modified version of your code:

echo "<img src=\"";
if ( $postid && get_post_thumbnail_id( $postid)) {
  $thumb_url = wp_get_attachment_image_src( get_post_thumbnail_id( $postid), 'thumbnail', false );
  $thumb_url = $thumb_url[0];
  echo $thumb_url;
}
else{
  echo "http://www.website.com/default.jpeg";
}                          
echo "\">"; 

I would add that in the future, a good rule of thumb when coding is to take things a step at a time, rather than writing a whole bunch of code at once. Do it one line at a time and make sure that your variables contain the expected output before moving on to the next step. Otherwise, you can end up with a chunk of code like this that actually has problems in several spots and it can be difficult and/or time consuming to try and figure out why it’s not working.