With the default [gallery]
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:
[gallery]
[gallery id=42]
Or you can create a gallery by explicitly specifying all the attachment IDs:
[gallery include="23,39,45"]
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: [gallery id=this,8]
. 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 );
}