Condition, show container if gallery contains more than 2 images

Hi, i’m using JetEngine Custom post types with the Gallery field set to “Array with media ID and URL”. I want to use conditions to show a container if the current posts gallery contains 2 or more images, otherwise don’t display it. I tried Filters: Dynamic Data – Bricks Academy. But The only thing that gets returned is the image names. I want the number of images in the current posts gallery array.

Does anyone have any idea or other solutions?
Thank You!

Hey @BagOfBricks,

you could write a small custom function to return the number of images the gallery contains:

function gallery_image_count() {
    $field_name = 'event_gallery';
    $gallery = get_post_meta( get_the_ID(), $field_name, true );
    return count( $gallery );
}

You could then use this function in your condition:

{echo:gallery_image_count}

Remember to whitelist the function (see academy article):

add_filter( 'bricks/code/echo_function_names', function() {
    return [
        'gallery_image_count',
    ];
} );

Best,

André

1 Like

Genius @aslotta! Got it to work perfectly :yellow_heart:

This is the code I used where I removed the $field_name (Might be worse, let me know). I used the bellow code in the “PHP & HTML” part of the Code element. Including the <?php?> wrapper. Use {echo:gic} in a heading to see the current amount of images.

“gic” will be changed to something readable later, ‘bilder’ is just the slug I chose for the JetEngine Gallery field.

<?php
function gic() {
    $gallery = get_post_meta( get_the_ID(), 'bilder', true );
    return count( $gallery );
}
?>

For others, a mistake you should not make is adding the filter part to the “style.css” and then wonder why nothing gets fetched. Instead click the tiny button that says “functions.php” under “style.css” in your theme file editor, and add the filter there.

Hi, I’m trying to use this with a Pods custom field gallery. This is what I have, but it’s not working:

<?php
function gallery_image_count() {
    $field_name = 'member_instruments';
    $gallery = $pod->field( [
    'name' => 'member_instruments',
    'output' => 'ids',
] );
    return count( $gallery );
}
?>  

Many thanks.

This seems to be working for a pods custom gallery field:

<?php
function gallery_image_count() {
   
    $pod = pods();
     // Define the field name
    $field_name = 'member_instruments';
    $gallery = $pod->field($field_name, array('output' => 'ids'));
     // Return the count of items if $gallery is an array, otherwise return 0
    return is_array($gallery) ? count($gallery) : 0;
}
?>