The get_post_gallery WordPress PHP filter allows you to modify the first-found post gallery in a WordPress post.
Usage
add_filter('get_post_gallery', 'your_custom_function', 10, 3); function your_custom_function($gallery, $post, $galleries) { // your custom code here return $gallery; }
Parameters
- $gallery (array) – The first-found post gallery in the post.
- $post (int|WP_Post) – The post ID or the WP_Post object.
- $galleries (array) – Associative array containing all found post galleries in the post.
More information
See WordPress Developer Resources: get_post_gallery
Examples
Change the order of images in the gallery
Reverse the order of images in the first-found gallery:
add_filter('get_post_gallery', 'reverse_gallery_images', 10, 3); function reverse_gallery_images($gallery, $post, $galleries) { if (!empty($gallery['ids'])) { $gallery['ids'] = implode(',', array_reverse(explode(',', $gallery['ids']))); } return $gallery; }
Limit the number of images in the gallery
Limit the number of images in the first-found gallery to 3:
add_filter('get_post_gallery', 'limit_gallery_images', 10, 3); function limit_gallery_images($gallery, $post, $galleries) { if (!empty($gallery['ids'])) { $image_ids = explode(',', $gallery['ids']); $gallery['ids'] = implode(',', array_slice($image_ids, 0, 3)); } return $gallery; }
Remove a specific image from the gallery
Remove a specific image with ID 123 from the first-found gallery:
add_filter('get_post_gallery', 'remove_specific_image', 10, 3); function remove_specific_image($gallery, $post, $galleries) { if (!empty($gallery['ids'])) { $image_ids = explode(',', $gallery['ids']); $image_ids = array_diff($image_ids, array('123')); $gallery['ids'] = implode(',', $image_ids); } return $gallery; }
Display a custom message if the gallery is empty
Show a message if the first-found gallery is empty:
add_filter('get_post_gallery', 'display_custom_message_if_empty', 10, 3); function display_custom_message_if_empty($gallery, $post, $galleries) { if (empty($gallery['ids'])) { $gallery['custom_message'] = 'No images found in this gallery.'; } return $gallery; }
Add a custom attribute to the gallery shortcode
Add a custom attribute data-custom-attribute
to the gallery shortcode:
add_filter('get_post_gallery', 'add_custom_attribute', 10, 3); function add_custom_attribute($gallery, $post, $galleries) { $gallery['data-custom-attribute'] = 'custom value'; return $gallery; }