Meta Box Group’s Number Sub Field Values Sum

In the Bricks Facebook group a user asked:

I have a metabox clonable group. I have a field in there named “Price” and I’d like to add a “Total” field like in the image.

I’ve tried this with custom code, but I can’t seem to manage it since its in a query. Does bricks have a calculation possibility?

We can define a custom function that takes a Meta Box group ID, the sub field ID and optionally, the post ID and returns the total of the specified sub field values for all rows for a post (current one by default). Then echo this function in a Basic Text element in the Bricks editor.

Step 1

Set up a cloneable Meta Box group for your post type.

Edit the posts of your post type and populate the field.

Step 2

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

<?php

/**
 * Calculate the sum of a specific sub field across all groups in a Meta Box group field.
 *
 * @param string $group_field_id The ID of the Meta Box group field.
 * @param string $sub_field_id   The ID of the sub field to sum.
 * @param int    $post_id        Optional. The post ID. Defaults to the current post.
 * 
 * @return float The sum of the specified sub field values.
 */
function bl_calculate_meta_box_group_sum( string $group_field_id, string $sub_field_id, int $post_id = 0 ): float {
    // If no post ID is provided, use the current post ID
    if ( $post_id === 0 ) {
        $post_id = get_the_ID();
    }

    // Get the group field data
    $groups = rwmb_meta( $group_field_id, [], $post_id );

    // Initialize the sum
    $sum = 0;

    // Loop through each group row
    foreach ( $groups as $group ) {
        // Check if the sub field exists in the group row and is numeric
        if ( isset( $group[$sub_field_id] ) && is_numeric( $group[$sub_field_id] ) ) {
            // Add the sub field value to the sum
            $sum += (float) $group[$sub_field_id];
        }
    }

    // Return the total sum
    return $sum;
}

Step 3

Whitelist the bl_calculate_meta_box_group_sum function.

Ex.:

<?php 

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

You should also add other functions (native or custom) being used in your Bricks instance besides bl_calculate_meta_box_group_sum. This can be checked at Bricks → Settings → Custom code by clicking the Code review button.

More info on whitelisting can be found here.

Step 4

Edit the Bricks template that applies to single posts of your post type.

Set up a query loop whose type is your Meta Box group

Below that, add a Basic Text element and change its text to:

Total: ${echo:bl_calculate_meta_box_group_sum(services,price)}

where services is the Meta Box group-type field ID and price is the number-type sub field ID.

Here‘s the JSON of the Section if you want to quickly copy and paste.

Reference

https://docs.metabox.io/functions/rwmb-meta/