1

I have a piece of code in my website's header.php that can generate og:image meta data for FB sharing. It works perfectly when the given post has a featured image.

<?php $fb_image = wp_get_attachment_image_src(get_post_thumbnail_id( get_the_ID() ), '480'); ?>
<?php if ($fb_image) : ?>
  <meta property="og:image" content="<?php echo $fb_image[0]; ?>" />
<?php endif; ?>

I would grateful if you could tell me how to modify (or replace) this code to get an og:image meta tag even if the post has 1 or more photos, but none of them are set as featured.

  • Facebook do it automatically. If og tag missing and content has suitable image! – Sumit Mar 29 '16 at 6:41
  • Sumit is right. If you need it anyway try catching the first image in post content like that css-tricks.com/snippets/wordpress/… – Zlatev Mar 29 '16 at 6:43
4

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).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.