Skip to content

Snippets / PHP

PHP

Pull First Gallery Field Image for Open Graph Meta Image

D Donald McGuinn · 261 views · Updated 2 years ago
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
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 · 18 lines

Discussion

Ask a question or share how you used this.

Log in to join the discussion.

No comments yet — be the first.

Voxel Guide assistant
Ask about snippets, addons & how-tos

Hey — how can I help?

I can dig through the library for snippets, addons, and tutorials.

AI can be wrong — double-check anything important.