Support

Account

Home Forums General Issues Modify function to take start argument and no of pictures

Solved

Modify function to take start argument and no of pictures

  • I am using this function to display a gallery thumbnail:

    function allphotos_shortcode(){
    
      $images = get_field('fl_gallery');
    
      if( $images ) {
          $output .= '<ul id="kalpht">';
          foreach( $images as $image ) :
                  $output .= '<li><a class="x-img-link" href="' . $image['url'] .'" data-options="thumbnail:\'' . $image['sizes']['mini-me'] . '\'"><img src="' . $image['sizes']['mini-me'] . '" alt="' . $image['alt'] . '" /></a></li>';
             endforeach;
          $output .= '</ul>' . do_shortcode('[lightbox opacity="0.9" thumbnails="true"]');
    }
    
    return $output;
     }
    
    add_shortcode('allphotos', 'allphotos_shortcode');

    I am looking to modify it so I can specify in the arguments the starting position and the number of images I want to retrieve.

    So for example: [allphotos start=”2″ number=”4″] will start from image 2 and display the next 4 images. “fl_gallery” is a standard ACF gallery field. Any ideas?

  • add_shortcode’s callback accepts 2 parameters. The first one being the attributes and the second on is the body content. https://developer.wordpress.org/reference/functions/add_shortcode/

    Then you can use php’s array_slice to to slice the array with a starting index and length. http://php.net/manual/en/function.array-slice.php

    So, you callback will look something like this:

    
    function allphotos_shortcode($attrs) {
        $attrs = shortcode_atts([
            'start' => 0,
            'number' => null,
        ], $attrs);
    
        if (! $images = get_field('fl_gallery')) {
            return '';
        }
    
        if (! $images = array_slice($images , $attrs['start'], $attrs['number'])) {
            return '';
        }
    
        $output .= '<ul id="kalpht">';
        foreach ($images as $image) {
            $output .= sprintf(
                '<li><a class="x-img-link" href="%s" data-options="%s">%s</a></li>',
                $image['url'],
                "thumbnail:'{$image['sizes']['mini-me']}'",
                wp_get_attachment_image($image['id'], 'mini-me')
            );
        }
        $output .= '</ul>' . do_shortcode('[lightbox opacity="0.9" thumbnails="true"]');
    
        return $output;
    }

    cheers

  • This reply has been marked as private.
Viewing 3 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic.