Search code examples
wordpressgalleryshortcode

How do I utilize default gallery output options in a customized gallery shortcode?


My end goal in all of this is to create a gallery page that automatically uploads images attached to any published post on the site. In my search I found the code below (also found here), placed it in my fucntions.php and it works great, BUT I can't use any of the other gallery output options (size, order, orderby, etc...) to help organize the images in the way I want. Looking at the code it seems as if I need to add/introduce the other output options, but being very new to this, I'm not sure how to modify the code below to make this happen. Any thoughts?

/**
* Usage: [catgallery cat="4,5"]
* Attribute: array of category IDs
*/

add_shortcode('catgallery', 'wpse_70989_cat_gallery_shortcode');

function wpse_70989_cat_gallery_shortcode($atts) 
{
  // $return = ''; // DEBUG: enable for debugging

  $arr = array();
  $cat_in = explode( ',', $atts['cat'] );
  $catposts = new WP_Query( array(
      'posts_per_page'    => -1
  ,   'category__in'      => $cat_in
  ) );

  foreach( $catposts->posts as $post)
  {

    // DEBUG: Enable the next line to print the post title
    // $return .= '<strong>' . $post->post_title . '</strong><br />';

    $args = array( 
        'post_type'     => 'attachment'
    ,   'numberposts'   => -1
    ,   'post_status'   => null
    ,   'post_parent'   => $post->ID 
    ); 
    $attachments = get_posts($args);

    if ($attachments) 
    {
        foreach ( $attachments as $attachment ) 
        {
            // DEBUG: Enable the next line to debug the attachement object
            // $return .= 'Attachment:<br /><pre>' . print_r($attachment, true) . '</pre><br />';
            $arr[] = $attachment->ID;
        }
    }

  }

  // DEBUG: Disable the next line if debugging 
  $return = do_shortcode( '[gallery include="' . implode( ',', $arr ) . '"]' );
  return $return;
}

Solution

  • The default Wordpress gallery comes with orderby and size options as specifed here so just add which option you like to the do_shortcode line.

    If you want something more complex, you may have to develop a custom plugin.