If you want to display the attached image gallery, from another post, you can use:
[gallery id="123"]
where the custom id
attribute is the post ID.
If you want limit the number of items in a gallery, you can use:
[gallery items="2"]
where the custom items
attribute is the maximum number of items to display.
This attribute is supported by the following plugin:
<?php
/**
* Plugin Name: The Gallery Shortcode - Maximum Number Of Items.
* Description: Support the 'items' attribute in the gallery shortcode
* Plugin URI: http://wordpress.stackexchange.com/a/176937/26350
* Plugin Author: Birgir Erlendsson (birgire)
* Version: 0.0.1
*/
add_action( 'init', function()
{
if( class_exists( 'LimitGalleryItems' ) )
{
$o = new LimitGalleryItems;
$o->init();
}
} );
class LimitGalleryItems
{
private $items;
public function init()
{
add_filter( 'post_gallery', array( $this, 'post_gallery' ), 10, 3 );
}
public function post_gallery( $output = '', $attr = array(), $instance = 0 )
{
if( isset( $attr['items'] ) )
{
$this->items = $attr['items'];
add_filter( 'query', array( $this, 'query' ) );
}
return $output;
}
public function query( $sql )
{
remove_filter( current_filter(), array( $this, __FUNCTION__ ) );
return preg_replace( '#LIMIT 0,\s\d+#', sprintf( "LIMIT 0, %d", $this->items ) , $sql );
}
} // end class
Since the gallery shortcode is using get_posts()
or get_children()
, to fetch the gallery images, there's no direct way to filter those queries. Not even to change the suppress_filter
attribute.
First I wrote a solution that chops down the number of images in the ids
/include
parameters, but that will not work for when the id
attribute is set.
Then I wrote a solution that just duplicated the get_children()
in the gallery to generate a new chopped list of ids
, to include again in the gallery_shortcode()
function via the post_gallery
filter. But I didn't like this solution since then we have to query the images twice!
So therefore I choose the query
filter to directly modify the LIMIT
of the generated SQL query. This should work no matter what combination of shortcode attributes you use.