Get the First or Featured Image URL in WordPress

In a previous post I covered how to get the first or Featured Image in WordPress for displaying the image, but sometimes just the image URL is needed for Open Graph and Twitter Card header tags, etc. The method below first checks for a Featured Image, then for the first attached image, and finally a default image if needed. This also allows you to designate the size (thumbnail, medium, large or full), and it outputs the image URL without the img tag and associated image attributes.

<?php
function evo_thumbnail_image_url() {
	if ( has_post_thumbnail() ) {
		the_post_thumbnail_url( 'large' );
	} else {
		global $post;
		$args = array(
			'post_type'      => 'attachment',
			'numberposts'    => -1,
			'post_mime_type' => 'image',
			'post_status'    => null,
			'post_parent'    => $post->ID,
			'posts_per_page' => 1
		);
		$attachments = get_posts( $args );
		if ( $attachments ) {
			foreach ( $attachments as $attachment ) {
				$src = wp_get_attachment_image_src( $attachment->ID, 'large' );
				if ( $src ) {
					echo $src[0];
				}
			}
		} else {
			echo get_stylesheet_directory_uri() . '/assets/images/default-post-image.png';
		}
	}
}

Use the function in the loop like this.

<?php evo_thumbnail_image_url(); ?>

If only the Featured Image URL is needed, the method below will work.

<?php the_post_thumbnail_url( 'large' ); ?>