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.
<?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.
*/functionbl_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 IDif ( $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 rowforeach ( $groupsas$group ) {
// Check if the sub field exists in the group row and is numericif ( 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 sumreturn$sum;
}
Step 3
Whitelist the bl_calculate_meta_box_group_sum function.
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.