Count of Images in Meta Box Image Advanced Field

In the BricksLabs Facebook group a user asks:

Is there a way to count images inside a post that uses metabox image upload ?

This Pro tutorial provides the code for getting the count of the number of images in an Image Advanced type of custom field created using Meta Box.

We are going to define a custom function and can then use it with the Dynamic data tag in Bricks to, for example, conditionally render a Section only if there is at least one image uploaded/selected to/for the field.

with the Dynamic data being

{echo:bl_get_image_count_image_advanced(image_advanced_vsoh9ful7jb)}

where image_advanced_vsoh9ful7jb is the field ID.

Add the following in child theme‘s functions.php (w/o the opening PHP tag) or a code snippets plugin:

// prevent "Fatal error: Uncaught Error: Call to undefined function rwmb_get_value()" if Meta Box is not active.
if ( ! function_exists( 'rwmb_get_value' ) ) {
  function rwmb_get_value( $key, $args = [], $object_id = null ) {
      return null;
  }
}

// Function to get the count of number of images in Meta Box Image Advanced field
function bl_get_image_count_image_advanced( $field_id, $object_id = null ) {
  $images = rwmb_get_value( $field_id );

  return isset( $images ) && is_array( $images ) ? count( $images ) : 0;
}

We have set two parameters for the bl_get_image_count_image_advanced function: $field_id and $object_id.

$object_id, if not provided when the function is called defaults to the current object (post/term/user) ID. This parameter is useful when the custom field is present on a Settings page instead of on a post/Page/CPT/term/user.

Now the function is ready to be used. Remember to pass in the field ID as its argument.

References

https://docs.metabox.io/functions/rwmb-get-value/