Blog

WordPress Image Source Function

It’s a little frustrating that WordPress’s wp_get_attachment_image_src function returns an array instead of just a URL; instead, the function returns the src, width, and height:

<?php list( $src, $width, $height ) = wp_get_attachment_image_src( get_post_thumbnail_id(), 'thumb' ); ?>

We often don’t need to know the width and height of the returned source since we normally send a size like ‘thumb’ to that function as input. Below is an image source function that you can add to your functions.php file that only returns the URL of the image source and also uses a default image if no source was found (which is useful if a post doesn’t include a Featured Image or post thumbnail):

The function above allows us to use a function call directly in our image src like this:

<img src="<?php _e( get_image_src( get_post_thumbnail_id(), 'thumb' ) ); ?>" />