As was already stated, Facebook automatically detects images if the OG image tag is missing. However, in some cases, it might detect other images (e.g. not from your post but from other content).
In that case, it can be useful to fetch a list of all images attached to the post and use the one you like, or, as you suggest, the first one. The example below fetches the first image attachment of the post using get_posts
, then retrieves the associated thumbnail image, and displays the image URL. You can use the image URL, stored in $thumbnail[0]
, along with its width and height, which are stored in $thumbnail[1]
and $thumbnail[2]
, respectively.
$images = get_posts( array(
'post_parent' => get_the_ID(),
'post_type' => 'attachment',
'numberposts' => 1, // Single attachment
'post_status' => null,
'post_mime_type' => 'image', // Only images
'orderby' => 'post_date',
'order' => 'ASC'
) );
if ( ! empty( $images ) ) {
$thumbnail = wp_get_attachment_image_src( $images[0]->ID, 'thumbnail' );
echo $thumbnail[0];
}
Bear in mind that this code does not fetch the first image that is in the post per se, but the first attachment to the post that is an image. In most cases, these two are the same (if you don’t attach images to your posts other than for inserting them into the post content, they’re the same).