Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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:

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:

[gallery type="squares" category="alpha" order="DESC" orderby="ID" link="file"]

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 . "\n\t\t" . $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 . "\n\t\t" . $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( '[gallery link="file" columns="5" order="DESC" orderby="ID" include="' . $people_ids . '"]' );

?>

<?php var_dump( $people_id_array ); ?>

<?php // get_sidebar(); ?>

<?php get_footer(); ?>

Working now

share|improve this question
    
Re: Notice: Undefined property - check carefully for syntax errors, and spelling errors. $people_attachments returns a valid query object, so you shouldn't be seeing that error. –  Chip Bennett Apr 16 at 11:52
    
I copied the complete code, as you can see. Did YOU find any syntax error? I could not. –  vega Apr 16 at 15:06
    
That error is telling you that $people_attachments isn't a valid query object. You need to debug to find out why. –  Chip Bennett Apr 16 at 15:09
1  
change while ( $alpha_attachments->have_posts ) to while ( $alpha_attachments->have_posts() ) - there is a missing set of () –  Stephen S. Apr 16 at 17:24
1  
@vega you should consider marking this question as answered and opening up a new question regarding the image size as they are separate topics –  Stephen S. Apr 17 at 15:27

1 Answer 1

up vote 2 down vote accepted

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 as $alpha ) {
        $alpha_id_array[] = $alpha->ID;
    }
    
    $alpha_ids = implode( ',', $alpha_id_array );
    
    echo do_shortcode( '[gallery include="' . $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 . '"]' );
share|improve this answer
    
Thank you very much, but two questions: 1. As I have 3 categories, do I have to use that code three times in my child functions.php with each category stated? 2. I wanted to use the text field in the Wordpress menu for pages and that does not support PHP code like "echo do_shortcode( '[gallery include="' . $gallery_ids . '"]' );", right? How would I have to address that there then? –  vega Apr 13 at 19:54
    
There are lots of ways to do that. You could create three different custom page templates (one for each category), or you could create one custom page template, and then use post custom meta data to pass the category slug to the custom query. In either case, you would need three separate static pages, one for each category. Or, you could create one custom page template, and output all three galleries on the same page, just replicating the code for each gallery. –  Chip Bennett Apr 13 at 20:06
    
Ah, shit, I see. I thought I could still keep the dynamic nature without creating custom page templates and using the standard pages given. So, putting [gallery include="' . $gallery_ids . '"] just into the text field menu of Wordpress pages will not work, I guess. :-\ Here the link for the site, btw, if that helps. www.studio-scs.de (under development, of course). –  vega Apr 13 at 20:08
    
I added to my first post, because I still could not reply to it. Is that correct that way then or did I misunderstand you? –  vega Apr 13 at 20:27
    
Yes, editing your question with updated code that you've tried is correct; thank you for that. But honestly, I'm not sure what you're trying to do with all that code, or how it relates specifically to passing attachments with a particular category to the [gallery] shortcode. –  Chip Bennett Apr 13 at 20:56

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.