Featured image alternatives on three levels
If you forget or can’t set a featured image, it won’t look very good on your website.
The following code snippet offers a solution. It checks if the featured image is set, if not it uses the last image attachment uploaded to the page. If neither is available, it uses the random image from the picsum photo.
<?php
if ( has_post_thumbnail() ) {
the_post_thumbnail_url();
} else {
$attachments = get_children( array(
'post_parent' => get_the_ID(),
'post_type' => 'attachment',
'post_mime_type' => 'image'
) );
if ( $attachments ) {
$last_attachment = array_pop( $attachments );
$image_url = wp_get_attachment_url( $last_attachment->ID );
echo '' . $image_url . '';
} else {
echo 'https://picsum.photos/660/440';
}
}
?>