Código que verifica se o post tem uma imagem destacada selecionada, caso não tenha, ele vai pegar a primeira imagem inserida no post:
/**
* get post image
*
* @author Difluir
* @link https://code.difluir.com/
*
*/
if ( ! function_exists('difluir_get_post_image') ) :
function difluir_get_post_image( $post_id = '', $image_size = '' ) {
//if hasn't post id
if ( ! $post_id ) {
$post_id = absint( get_the_ID() );
}
//if hasn't image size
if ( ! $image_size ) {
$image_size = 'large';
}
//start
$image = '';
if ( has_post_thumbnail($post_id) ) {
$image = wp_get_attachment_image_src( get_post_thumbnail_id($post_id), $image_size );
}
elseif ( is_attachment() && wp_attachment_is_image($post_id) ) {
$image = wp_get_attachment_image_src( $post_id, $image_size );
}
else {
$imgs = get_posts( array( 'post_type' => 'attachment', 'post_mime_type' => 'image', 'numberposts' => 1, 'orderby' => 'menu_order', 'order' => 'ASC', 'post_status' => 'null', 'post_parent' => $post_id ) );
if ( $imgs ) {
foreach ( $imgs as $ig ) {
$image = wp_get_attachment_image_src( $ig->ID, $image_size );
}
}
}
//return image
return $image;
}
endif;
Para mostrar o thumbnail no loop:
if ( difluir_get_post_image() ) {
$img = difluir_get_post_image();
echo '<img src="'.esc_url( $img[0] ).'" width="'.esc_attr( $img[1] ).'" height="'.esc_attr( $img[2] ).'" alt="" />';
}
Detalhe: esse código funciona apenas para pegar as imagens inseridas no post, que foram feitas upload enquanto escrevia o post. Se quiser pegar a primeira imagem do post, independente de onde ela tenha sido feito upload, usar esse outro código (dá até pra inserir ele como fallback aqui).