Add Gallery Images as Extra Open Graph Images in Yoast
Adds the images from a gallery custom field as additional og:image tags through Yoast SEO, so social networks can offer a choice of preview.
Opens WPIDE on
Code
// Meta key holding attachment IDs.
$wpide_og_gallery_field = 'gallery';
// Maximum number of extra images.
$wpide_og_gallery_max = 3;
add_action( 'wpseo_add_opengraph_additional_images', function ( $container ) use ( $wpide_og_gallery_field, $wpide_og_gallery_max ) {
if ( ! is_singular() || ! is_object( $container ) || ! method_exists( $container, 'add_image_by_url' ) ) {
return;
}
$ids = get_post_meta( get_queried_object_id(), $wpide_og_gallery_field, true );
$ids = array_slice( array_filter( array_map( 'absint', is_array( $ids ) ? $ids : explode( ',', (string) $ids ) ) ), 0, $wpide_og_gallery_max );
foreach ( $ids as $id ) {
$url = wp_get_attachment_image_url( $id, 'large' );
if ( $url ) {
$container->add_image_by_url( $url );
}
}
} );
Notes
The field may hold an array of attachment IDs or a comma-separated list. Most networks use only the first image.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.