Limit the number of gallery items WordPress outputs

<?php echo do_shortcode(''); ?>

That’s the code I’m using, I need a way to limit it to 2 items instead of all items. I know there is no native way to do it with the gallery shortcode, but is there a plugin or alternative method I could use?

Related posts

Leave a Reply

1 comment

  1. you can rewrite the gallery shortcode function in your template’s functions.php and do something like this

    remove_shortcode('gallery');
    add_shortcode('gallery', 'parse_gallery_shortcode');
    function parse_gallery_shortcode($atts) {
    
    global $post;
    
    extract(shortcode_atts(array(
    'order'      => 'ASC',
    'orderby'    => 'menu_order ID',
        'id' => $post->ID,
        'itemtag' => 'dl',
        'icontag' => 'dt',
        'captiontag' => 'dd',
        'columns' => 3,
        'ids' => '',
        'size' => 'medium',
        'link' => 'file'
    ), $atts));
    
    $ids = explode(',', $atts[ids]);
    $i = 0;
    foreach( $ids as $id ) {
        $i++;
        if ( $i > 2 ) { break; } 
        // or replace 2 with how many images you want
    $image  = get_post($id);
    $img = wp_get_attachment_image_src($image->ID, 'post-onephoto');
    $largeimg = wp_get_attachment_image_src($image->ID, 'large');
    // this is where you output your images the way you want it
    $return .= '<a href="'.$largeimg[0].'"><img width="400" height="400" src="'.$img[0].'" /></a>'; 
    }
    
     return $return;
    }