Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

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

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.