Pull First Gallery Field Image for Open Graph Meta Image

Description/Instructions

This snippet will pull the first image from the “gallery” field on your single post and will use that as the OG:IMAGE when sharing the link.

THIS CODE ONLY WORKS WITH SEOPRESS PLUGIN

If this snippet helped, feel free to buy me a taco :)

Instructions

SEOPRESS PLUGIN ONLY

function sp_social_og_thumb_dynamic_multiple_ids($html) {
if (is_single()) {
global $post;
$image_ids_string = get_post_meta($post->ID, 'gallery', true); // Assuming this returns a string of comma-separated IDs
$image_ids = explode(',', $image_ids_string); // Split the string into an array of IDs

if (!empty($image_ids)) {
$first_image_id = trim($image_ids[0]); // Get the first ID and trim whitespace
$first_image_url = wp_get_attachment_url($first_image_id); // Get the full URL of the image

if ($first_image_url) {
$html = '<meta property="og:image" content="' . esc_url($first_image_url) . '" />';
}
}
}
return $html;
}
add_filter('seopress_social_og_thumb', 'sp_social_og_thumb_dynamic_multiple_ids');

  • PHP
Copy Code

Let's Chat About this Snippet