Using WordPress ‘get_post_galleries’ PHP filter

The get_post_galleries WordPress PHP filter allows you to modify the list of all found galleries in a given post.

Usage

add_filter( 'get_post_galleries', 'your_custom_function', 10, 2 );

function your_custom_function( $galleries, $post ) {
    // your custom code here
    return $galleries;
}

Parameters

  • $galleries (array) – Associative array of all found post galleries.
  • $post (WP_Post) – Post object.

More information

See WordPress Developer Resources: get_post_galleries

Examples

Remove empty galleries

Remove galleries with no images from the list of galleries.

add_filter( 'get_post_galleries', 'remove_empty_galleries', 10, 2 );

function remove_empty_galleries( $galleries, $post ) {
    foreach ( $galleries as $key => $gallery ) {
        if ( empty( $gallery['src'] ) ) {
            unset( $galleries[ $key ] );
        }
    }
    return $galleries;
}

Limit the number of galleries

Limit the number of displayed galleries to a specific number.

add_filter( 'get_post_galleries', 'limit_galleries', 10, 2 );

function limit_galleries( $galleries, $post ) {
    $max_galleries = 3;
    return array_slice( $galleries, 0, $max_galleries, true );
}

Add a custom attribute to each image in the galleries.

add_filter( 'get_post_galleries', 'add_custom_attribute', 10, 2 );

function add_custom_attribute( $galleries, $post ) {
    foreach ( $galleries as $key => $gallery ) {
        foreach ( $gallery['src'] as $index => $src ) {
            $galleries[ $key ]['src'][ $index ] = $src . ' data-custom-attribute="value"';
        }
    }
    return $galleries;
}

Change the order of galleries

Reverse the order of galleries.

add_filter( 'get_post_galleries', 'reverse_galleries_order', 10, 2 );

function reverse_galleries_order( $galleries, $post ) {
    return array_reverse( $galleries, true );
}

Modify galleries based on post category

Customize galleries based on the post’s category.

add_filter( 'get_post_galleries', 'modify_galleries_by_category', 10, 2 );

function modify_galleries_by_category( $galleries, $post ) {
    if ( has_category( 'special', $post ) ) {
        // Perform custom modifications for 'special' category
        // ...
    }
    return $galleries;
}