Home › Forums › General Issues › 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
The topic ‘Modify function to take start argument and no of pictures’ is closed to new replies.
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.