Connecting WordPress gallery to custom categories (taxonomy)

I want to use the WordPress gallery to show all pictures of one category in a gallery (on a fixed page), which I do not have to update all the time by inserting the pictures manually.

So I added the category feature into media with this function:

Read More
function is_add_categories_to_attachments() {
register_taxonomy_for_object_type( 'category', 'attachment' );
}
add_action( 'init' , 'is_add_categories_to_attachments' );

Great, that worked. In the media menu I can add as many categories I want to now. In my case I made three of them, named alpha, beta and gamma.

Then I wanted to post a gallery on a fixed page with one category:


But that did not work and I had to use the post_gallery filter in my child’s functions.php, so that I can change the code there, but I have absolutely NO CLUE how to enter the category recognisation into that gallery_shortcut:

function is_gallery($output, $attr) {
$post = get_post();

static $instance = 0;
$instance++;

if ( ! empty( $attr['ids'] ) ) {
    // 'ids' is explicitly ordered, unless you specify otherwise.
    if ( empty( $attr['orderby'] ) )
        $attr['orderby'] = 'post__in';
    $attr['include'] = $attr['ids'];
}

// Allow plugins/themes to override the default gallery template.
$output = apply_filters('post_gallery', '', $attr);
if ( $output != '' )
    return $output;

// We're trusting author input, so let's at least make sure it looks like a valid orderby statement
if ( isset( $attr['orderby'] ) ) {
    $attr['orderby'] = sanitize_sql_orderby( $attr['orderby'] );
    if ( !$attr['orderby'] )
        unset( $attr['orderby'] );
}

extract(shortcode_atts(array(
    'order'      => 'ASC',
    'orderby'    => 'menu_order ID',
    'id'         => $post ? $post->ID : 0,
    'itemtag'    => 'dl',
    'icontag'    => 'dt',
    'captiontag' => 'dd',
    'columns'    => 3,
    'size'       => 'thumbnail',
    'include'    => '',
    'exclude'    => '',
    'link'       => ''
), $attr, 'gallery'));

$id = intval($id);
if ( 'RAND' == $order )
    $orderby = 'none';

if ( !empty($include) ) {
    $_attachments = get_posts( array('include' => $include, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) );

    $attachments = array();
    foreach ( $_attachments as $key => $val ) {
        $attachments[$val->ID] = $_attachments[$key];
    }
} elseif ( !empty($exclude) ) {
    $attachments = get_children( array('post_parent' => $id, 'exclude' => $exclude, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) );
} else {
    $attachments = get_children( array('post_parent' => $id, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) );
}

if ( empty($attachments) )
    return '';

if ( is_feed() ) {
    $output = "n";
    foreach ( $attachments as $att_id => $attachment )
        $output .= wp_get_attachment_link($att_id, $size, true) . "n";
    return $output;
}

$itemtag = tag_escape($itemtag);
$captiontag = tag_escape($captiontag);
$icontag = tag_escape($icontag);
$valid_tags = wp_kses_allowed_html( 'post' );
if ( ! isset( $valid_tags[ $itemtag ] ) )
    $itemtag = 'dl';
if ( ! isset( $valid_tags[ $captiontag ] ) )
    $captiontag = 'dd';
if ( ! isset( $valid_tags[ $icontag ] ) )
    $icontag = 'dt';

$columns = intval($columns);
$itemwidth = $columns > 0 ? floor(100/$columns) : 100;
$float = is_rtl() ? 'right' : 'left';

$selector = "gallery-{$instance}";

$gallery_style = $gallery_div = '';
if ( apply_filters( 'use_default_gallery_style', true ) )
    $gallery_style = "
    <style type='text/css'>
        #{$selector} {
            margin: auto;
        }
        #{$selector} .gallery-item {
            float: {$float};
            margin-top: 10px;
            text-align: center;
            width: {$itemwidth}%;
        }
        #{$selector} img {
            border: 2px solid #cfcfcf;
        }
        #{$selector} .gallery-caption {
            margin-left: 0;
        }
        /* see gallery_shortcode() in wp-includes/media.php */
    </style>";
$size_class = sanitize_html_class( $size );
$gallery_div = "<div id='$selector' class='gallery galleryid-{$id} gallery-columns-{$columns} gallery-size-{$size_class}'>";
$output = apply_filters( 'gallery_style', $gallery_style . "ntt" . $gallery_div );

$i = 0;
foreach ( $attachments as $id => $attachment ) {
    if ( ! empty( $link ) && 'file' === $link )
        $image_output = wp_get_attachment_link( $id, $size, false, false );
    elseif ( ! empty( $link ) && 'none' === $link )
        $image_output = wp_get_attachment_image( $id, $size, false );
    else
        $image_output = wp_get_attachment_link( $id, $size, true, false );

    $image_meta  = wp_get_attachment_metadata( $id );

    $orientation = '';
    if ( isset( $image_meta['height'], $image_meta['width'] ) )
        $orientation = ( $image_meta['height'] > $image_meta['width'] ) ? 'portrait' : 'landscape';

    $output .= "<{$itemtag} class='gallery-item'>";
    $output .= "
        <{$icontag} class='gallery-icon {$orientation}'>
            $image_output
        </{$icontag}>";
    if ( $captiontag && trim($attachment->post_excerpt) ) {
        $output .= "
            <{$captiontag} class='wp-caption-text gallery-caption'>
            " . wptexturize($attachment->post_excerpt) . "
            </{$captiontag}>";
    }
    $output .= "</{$itemtag}>";
    if ( $columns > 0 && ++$i % $columns == 0 )
        $output .= '<br style="clear: both" />';
}

$output .= "
        <br style='clear: both;' />
    </div>n";

return $output;
}
add_filter("post_gallery", "is_gallery",10,2);

Can you show me how to insert the category feature into the galley_shortcode?

Thank you in advance.


Would that be correct then?

function is_gallery($output, $attr) {
$post = get_post();

static $instance = 0;
$instance++;

if ( ! empty( $attr['ids'] ) ) {
// 'ids' is explicitly ordered, unless you specify otherwise.
if ( empty( $attr['orderby'] ) )
    $attr['orderby'] = 'post__in';
$attr['include'] = $attr['ids'];
}

// Allow plugins/themes to override the default gallery template.
$output = apply_filters('post_gallery', '', $attr);
if ( $output != '' )
return $output;

// We're trusting author input, so let's at least make sure it looks like a valid     orderby statement
if ( isset( $attr['orderby'] ) ) {
$attr['orderby'] = sanitize_sql_orderby( $attr['orderby'] );
if ( !$attr['orderby'] )
    unset( $attr['orderby'] );
}

extract(shortcode_atts(array(
'order'      => 'ASC',
'orderby'    => 'menu_order ID',
'id'         => $post ? $post->ID : 0,
'itemtag'    => 'dl',
'icontag'    => 'dt',
'captiontag' => 'dd',
'columns'    => 3,
'size'       => 'thumbnail',
'include'    => '',
'exclude'    => '',
'link'       => ''
), $attr, 'gallery'));

$id = intval($id);
if ( 'RAND' == $order )
$orderby = 'none';

$beta_attachments = new WP_Query( array(
'post_type' => 'attachment',
'post_status' => 'inherit',
'posts_per_page' => 0,
'category_name' => 'beta', // note: use category SLUG
) );

$beta_id_array = array();
foreach ( $beta_attachments as $beta ) {
$beta_id_array[] = $beta->ID;
}
$beta_ids = implode( ',', $beta_id_array );

$gamma_attachments = new WP_Query( array(
'post_type' => 'attachment',
'post_status' => 'inherit',
'posts_per_page' => 0,
'category_name' => 'gamma', // note: use category SLUG
) );

$gamma_id_array = array();
foreach ( $gamma_attachments as $gamma ) {
$gamma_id_array[] = $gamma->ID;
}
$gamma_ids = implode( ',', $gamma_id_array );

$alpha_attachments = new WP_Query( array(
'post_type' => 'attachment',
'post_status' => 'inherit',
'posts_per_page' => 0,
'category_name' => 'alpha', // note: use category SLUG
) );

$alpha_id_array = array();
foreach ( $alpha_attachments as $alpha ) {
$alpha_id_array[] = $alpha->ID;
}
$alpha_ids = implode( ',', $alpha_id_array );

if ( !empty($include) ) {
$_attachments = get_posts( array('include' => $include, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) );

$attachments = array();
foreach ( $_attachments as $key => $val ) {
    $attachments[$val->ID] = $_attachments[$key];
}
} elseif ( !empty($exclude) ) {
$attachments = get_children( array('post_parent' => $id, 'exclude' => $exclude, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) );
} else {
$attachments = get_children( array('post_parent' => $id, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) );
}

if ( empty($attachments) )
return '';

if ( is_feed() ) {
$output = "n";
foreach ( $attachments as $att_id => $attachment )
    $output .= wp_get_attachment_link($att_id, $size, true) . "n";
return $output;
}

$itemtag = tag_escape($itemtag);
$captiontag = tag_escape($captiontag);
$icontag = tag_escape($icontag);
$valid_tags = wp_kses_allowed_html( 'post' );
if ( ! isset( $valid_tags[ $itemtag ] ) )
$itemtag = 'dl';
if ( ! isset( $valid_tags[ $captiontag ] ) )
$captiontag = 'dd';
if ( ! isset( $valid_tags[ $icontag ] ) )
$icontag = 'dt';

$columns = intval($columns);
$itemwidth = $columns > 0 ? floor(100/$columns) : 100;
$float = is_rtl() ? 'right' : 'left';

$selector = "gallery-{$instance}";

$gallery_style = $gallery_div = '';
if ( apply_filters( 'use_default_gallery_style', true ) )
$gallery_style = "
<style type='text/css'>
    #{$selector} {
        margin: auto;
    }
    #{$selector} .gallery-item {
        float: {$float};
        margin-top: 10px;
        text-align: center;
        width: {$itemwidth}%;
    }
    #{$selector} img {
        border: 2px solid #cfcfcf;
    }
    #{$selector} .gallery-caption {
        margin-left: 0;
    }
    /* see gallery_shortcode() in wp-includes/media.php */
</style>";
$size_class = sanitize_html_class( $size );
$gallery_div = "<div id='$selector' class='gallery galleryid-{$id} gallery-columns-{$columns} gallery-size-{$size_class}'>";
$output = apply_filters( 'gallery_style', $gallery_style . "ntt" . $gallery_div );

$i = 0;
foreach ( $attachments as $id => $attachment ) {
if ( ! empty( $link ) && 'file' === $link )
    $image_output = wp_get_attachment_link( $id, $size, false, false );
elseif ( ! empty( $link ) && 'none' === $link )
    $image_output = wp_get_attachment_image( $id, $size, false );
else
    $image_output = wp_get_attachment_link( $id, $size, true, false );

$image_meta  = wp_get_attachment_metadata( $id );

$orientation = '';
if ( isset( $image_meta['height'], $image_meta['width'] ) )
    $orientation = ( $image_meta['height'] > $image_meta['width'] ) ? 'portrait' : 'landscape';

$output .= "<{$itemtag} class='gallery-item'>";
$output .= "
    <{$icontag} class='gallery-icon {$orientation}'>
        $image_output
    </{$icontag}>";
if ( $captiontag && trim($attachment->post_excerpt) ) {
    $output .= "
        <{$captiontag} class='wp-caption-text gallery-caption'>
        " . wptexturize($attachment->post_excerpt) . "
        </{$captiontag}>";
}
$output .= "</{$itemtag}>";
if ( $columns > 0 && ++$i % $columns == 0 )
    $output .= '<br style="clear: both" />';
}

$output .= "
    <br style='clear: both;' />
</div>n";

return $output;
}
add_filter("post_gallery", "is_gallery",10,2);

Update

hi Chip,

I understood your idea/solution now and tried it (well, copied it over thanks to you). I think the logic is working, but in practise use it does not. I used the code like that and it does not “see” the categories. Therefore it just shows an empty content (below navigation, of course).

people.php:

 <?php
 /**
 * Template Name: People Gallery
 */

 get_header(); ?>

<?php

$people_attachments = new WP_Query( array(
'post_type' => 'attachment',
'post_status' => 'inherit',
'posts_per_page' => 0,
'category_name' => 'people', // note: use category SLUG
) );

$people_id_array = array();

if ( $people_attachments->have_posts() ) : while ( $people_attachments->have_posts() ) : $people_attachments->the_post();

$people_id_array[] = get_the_ID();

endwhile; endif;
// Important!
wp_reset_postdata();

$people_ids = implode( ',', $people_id_array );

echo do_shortcode( '' );

?>

<?php var_dump( $people_id_array ); ?>

<?php // get_sidebar(); ?>

<?php get_footer(); ?>

Working now

Related posts

Leave a Reply

1 comment

  1. Edit

    If this is your goal:

    I want to use the WordPress gallery to show all pictures of one category in a gallery (on a fixed page), which I do not have to update all the time by inserting the pictures manually.

    Then the easiest way to accomplish it is via custom page template.

    Create the template

    1. Copy your page.php template file, and name it template-alpha-gallery.php

    2. At the top, add the following:

       <?php
       /**
        * Template Name: Alpha Gallery
        */
      
    3. Keep <?php get_header(); ?> and <?php get_footer(); ?>, and whatever HTML markup you need to keep. Delete the existing Loop code.

    4. Note: the template HTML/loop markup is very Theme-dependent. You’ll need to modify these instructions as appropriate for your current Theme.

    5. In place of the Loop code, add the shortcode output from below:

       $alpha_attachments = new WP_Query( array(
           'post_type' => 'attachment',
           'post_status' => 'inherit',
           'posts_per_page' => 0,
           'category_name' => 'alpha', // note: use category SLUG
       ) );
      
       $alpha_id_array = array();
      
       foreach ( $alpha_attachments->posts as $alpha ) {
           $alpha_id_array[] = $alpha->ID;
       }
      
       $alpha_ids = implode( ',', $alpha_id_array );
      
       echo do_shortcode( '[gallery ids="' . $gallery_ids . '"]' );
      
    6. Create a new Static Page, and assign it the “Alpha Gallery” page template

    7. Enjoy your gallery

    Original Answer

    The [gallery] shortcode doesn’t accept a “category” parameter, however, it does include an 'include' parameter, that accepts a comma-separated list of attachment IDs:

    [gallery include="1,2,3"]
    

    So, you can use include to list IDs for all of the attachments that have your specified category.

    First, query the correct attachments:

    $alpha_attachments = new WP_Query( array(
        'post_type' => 'attachment',
        'post_status' => 'inherit',
        'posts_per_page' => 0,
        'category_name' => 'alpha', // note: use category SLUG
    ) );
    

    Then, loop through and grab the IDs:

    Edit

    You need to WordPress loop through the results. Instead of this:

    $alpha_id_array = array();
    
    foreach ( $alpha_attachments as $alpha ) {
        $alpha_id_array[] = $alpha->ID;
    }
    

    …do this:

    $alpha_id_array = array();
    
    if ( $alpha_attachments->have_posts() ) : while ( $alpha_attachments->have_posts() ) : $alpha_attachments->the_post();
    
        $alpha_id_array[] = get_the_ID();
    
    endwhile; endif;
    // Important!
    wp_reset_postdata();
    

    Then, format the string:

    $alpha_ids = implode( ',', $alpha_id_array );
    

    Then, pass that string to the shortcode. If you’re using a custom page template, you can do it like so:

    echo do_shortcode( '[gallery include="' . $alpha_ids . '"]' );
    

    And that should be it.

    Edit

    When I click on the file, it loads the biggest available size. Can you tell me, where is the link creation or the expression for in which size to open. I created custom sizes vor example “gallerysize” or “blogsize”, but I do not know, how to use them here in this gallery.

    The [gallery] shortcode has a size parameter. Just add it to your output; for example, for “medium” images:

    echo do_shortcode( '[gallery size="medium" include="' . $alpha_ids . '"]' );