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

- Type: PHP
- Runs: Frontend only
- Category: [Plugin Integrations](https://wpide.com/library/category/integrations/)
- Tags: yoast, open-graph, gallery
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/yoast-og-extra-images/

## Code

```php
// 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 use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Add Gallery Images as Extra Open Graph Images in Yoast" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
