Support

Account

Home Forums Add-ons Gallery Field Conditional Implode statement for gallery in WP Gallery

Solved

Conditional Implode statement for gallery in WP Gallery

  • I’m displaying images from a gallery field in a WP Gallery using the snippet from the knowledgebase here http://www.advancedcustomfields.com/resources/gallery/#template-usage

    However, when there are no images added to the gallery field it throws an error:
    Warning: implode() [function.implode]: Invalid arguments passed

    Is there a way to modify the code below so that if there are no images it fails gracefully?

    <?php 
    $image_ids = get_field('gallery', false, false);
    $shortcode = '[gallery ids="' . implode(',', $image_ids) . '"]';
    echo do_shortcode( $shortcode );
    ?>
  • You need to add a conditional statement around your code so that it is not called if there are no images.

    
    <?php 
    $image_ids = get_field('gallery', false, false);
    if (is_array($image_ids)) {
        $shortcode = '[gallery ids="' . implode(',', $image_ids) . '"]';
        echo do_shortcode( $shortcode );
    }
    ?>
    
  • Thank you, this was perfect. Exactly what I needed!

Viewing 3 posts - 1 through 3 (of 3 total)

The topic ‘Conditional Implode statement for gallery in WP Gallery’ is closed to new replies.