Skip to content

Instantly share code, notes, and snippets.

@stephanieleary
Created August 1, 2012 21:31
Show Gist options
  • Save stephanieleary/3230957 to your computer and use it in GitHub Desktop.
Save stephanieleary/3230957 to your computer and use it in GitHub Desktop.
Multiple WordPress galleries per page using attachment tags
<?php
/*
Plugin Name: Tagged Galleries
Description: Lets you add multiple [gallery] tags in a single WordPress page. Specify the images to be included in each gallery using tags: [gallery tag="foo"] (assuming you have tagged the images).
Version: 1.0
Author: Stephanie Leary
Author URI: http://sillybean.net/
*/
add_action('admin_init', 'register_attachment_tags');
function register_attachment_tags() {
register_taxonomy_for_object_type('post_tag', 'attachment');
}
add_filter( 'post_gallery', 'tagged_gallery_shortcode', 9, 2);
function tagged_gallery_shortcode($output, $attr) {
global $post;
$ids = array();
// if tag="foo" was included in $attr, transform it into a comma-separated list of post IDs
if (isset($attr['tag'])) {
$tag = $attr['tag'];
if (term_exists($tag)) {
$posts = get_posts( array('post_type' => 'attachment', 'posts_per_page' => -1, 'post_parent' => $post->ID, 'tax_query' => array(
array(
'taxonomy' => 'post_tag',
'field' => 'slug',
'terms' => $tag
) )) );
$ids = array();
foreach ($posts as $apost) {
$ids[] = $apost->ID;
}
$ids = implode(',', $ids);
}
}
// now run the gallery shortcode as usual, using include=$ids in place of tag="foo"
extract(shortcode_atts(array(
'order' => 'ASC',
'orderby' => 'menu_order ID',
'id' => $post->ID,
'itemtag' => 'dl',
'icontag' => 'dt',
'captiontag' => 'dd',
'columns' => 3,
'size' => 'thumbnail',
'include' => '',
'exclude' => ''
), $attr));
if (!empty($ids))
$include = $ids;
// remove our filter so [gallery] will be processed as usual
remove_filter( 'post_gallery', 'tagged_gallery_shortcode', 9, 2);
$output = do_shortcode('[gallery
order="'.$order.'"
orderby = "'.$orderby.'"
id = "'.$id.'"
itemtag = "'.$itemtag.'"
icontag = "'.$icontag.'"
captiontag = "'.$captiontag.'"
columns = "'.$columns.'"
size = "'.$size.'"
include = "'.$include.'"
]');
// add our filter back so it's there the next time we encounter [gallery] in the content
add_filter( 'post_gallery', 'tagged_gallery_shortcode', 9, 2);
// return the gallery
return $output;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment