So let’s say I run a TV show blog. One day, the show releases to the public a set of 10 screencaps from an upcoming episode. I post that on my blog, either as a post with multiple images, or specifically as a “gallery” post — either way, readers can view all the image attached to that post as a gallery.
Then, several days and several posts later, they release 10 more screencaps from that same upcoming episode. I want to make a separate post rather than bump the old one, but I also somehow want to be able to display all screencaps (20) from that particular episode in a single gallery. Or at least what would look like a single gallery.
Possible? (Preferably without NextGEN or other plugins… trying to accomplish as much as I can using WordPress’ native capabilities before stacking plugins.)
With the default
shortcode there is no easy way to combine different galleries into one. You can either specify two different galleries: one of the current post and one of another post, specified by post ID:
Or you can create a gallery by explicitly specifying all the attachment IDs:
Specifying multiple post IDs will not work because gallery_shortcode()
uses get_children()
to get the attachments, which uses get_posts()
, which uses the standard WP_Query
class, and this only allows a numeric post_parent
value.
However, we can exploit the fact that there is a filter at the top of gallery_shortcode()
, that allows plugins to override the default gallery layout. The following example checks for an id
parameter with multiple IDs (or the special keyword this
), gets all the attachments of these posts, and puts them in an explicit include
attribute which is used to call the gallery function again. This allows you to combine different galleries like this:
. You can extend this idea to support other attributes too.
add_filter( 'post_gallery', 'wpse18689_post_gallery', 5, 2 );
function wpse18689_post_gallery( $gallery, $attr )
{
if ( ! is_array( $attr ) || array_key_exists( 'wpse18689_passed', $attr ) ) {
return '';
}
$attr['wpse18689_passed'] = true;
if ( false !== strpos( $attr['id'], ',' ) ) {
$id_attr = shortcode_atts( array(
'id' => 'this',
'order' => 'ASC',
'orderby' => 'menu_order ID',
), $attr );
$all_attachment_ids = array();
$post_ids = explode( ',', $id_attr['id'] );
foreach ( $post_ids as $post_id ) {
if ( 'this' == $post_id ) {
$post_id = $GLOBALS['post']->ID;
}
$post_attachments = get_children( array(
'post_parent' => $post_id,
'post_status' => 'inherit',
'post_type' => 'attachment',
'post_mime_type' => 'image',
'order' => $id_attr['order'],
'orderby' => $id_attr['orderby'],
), ARRAY_A );
$all_attachment_ids = array_merge( $all_attachment_ids, array_keys( $post_attachments ) );
}
$attr['include'] = implode( ',', $all_attachment_ids );
$attr['id'] = null;
}
return gallery_shortcode( $attr );
}