Categorias:

Pegar a primeira imagem inserida em um post, no WordPress

Função para pegar a primeira imagem do post:

/**
 * get first image in content
 *
 * @author Difluir
 * @link https://code.difluir.com/
 *
 */
if ( ! function_exists('difluir_get_first_image') ) :
	function difluir_get_first_image( $post_id = '', $content = '' ) {
		$first_img = '';

		//if hasn't post id
		if ( ! $post_id ) {
			$post_id = absint( get_the_ID() );
		}

		//if hasn't content
		if ( ! $content ) {
			$content_post = get_post( $post_id );
			$content      = $content_post->post_content;
		}

		//start
		ob_start();
		ob_end_clean();

		$output = preg_match_all( '/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $content, $matches );

		if ( isset($matches[1][0]) && !empty($matches[1][0]) ) {
			$first_img = esc_url( $matches[1][0] );
		}

		//return image
		return $first_img;
	}
endif;

Código para usar dentro do loop:

if ( difluir_get_first_image() ) {
	echo '<img src="'.difluir_get_first_image().'" alt="" />';
} else {
	echo 'No image found.';
}

Detalhe: esse código vai pegar a primeira imagem do post, mesmo que a imagem tenha sido feita upload em outro local. Se quiser pegar a imagem destacada, usar esse outro código.