How to calculate ACF fields in Frontend

I have 2 ACF Number Fields.

{acf_price} and {acf_cost_price}

I want to calculate the fields and get the profit price rendered on the frontend.
{acf_price} - {acf_cost_price} = value

I tried using the Dynamic Data to render PHP and used the following php code
{echo number_format(get_field(‘acf_price’) - get_field(‘acf_cost_price’), 2);}

But this just renders the code in plain text. Instead of calculating the Profit.

I also tried using this function as I found on another thread.

```add_filter( ‘bricks/dynamic_data/render_tag’, function( $tag, $post_id ) {

if ( $tag === 'acf_profit' ) {

    $price = (float) get_field( 'acf_price', $post_id );
    $cost_price  = (float) get_field( 'acf_cost_price', $post_id );

    if ( $price || $cost_price ) {
        $profit = $price - $cost_price;
        return number_format( $profit, 2 );
    }

    return '0.00';
}

return $tag;

}, 10, 2 );```


Then using the {acf_profit} in text field. I still get the code rendered instead of the value.

Hi,

  1. first of all, are you using it within a simple text field or a rich text field?

  2. generally, if you look for a tag like with if ( $tag === 'acf_profit' ) you have to include its brackets since the tag is named {acf_profit}.
    —> if ( $tag === {acf_profit}' )

  3. did you initialize the tag? like so:

add_filter('bricks/dynamic_tags_list', 'my_add_custom_tag_to_builder');
function my_add_custom_tag_to_builder($tags) {
  // ensure your tag is unique (best to prefix it)
  $tags[] = [
    'name'  => '{acf_profit}',
    'label' => 'Profit Data',
    'group' => 'Profit Data Group',
  ];

  return $tags;
}
  1. Then, use the bricks/dynamic_data/render_content filter.
    Within this, you can replace and render your custom tag directly in it:
add_filter( 'bricks/dynamic_data/render_content', function( $content, $post, $context ) {
  // test if tag appears in text field content (you may have more tags in it)
  if ( strpos( $content, '{acf_profit}' ) === false ) {
    return $content;
  }

  // get post id: mandatory!
  $post_id = is_object( $post ) ? $post->ID : (int) $post;

  // get acf_price field
  $price = (float) get_field( 'acf_price',  $post_id );

  // get acf_cost_price field
  $cost_price = (float) get_field( 'acf_cost_price', $post_id );

  // calculate and format number
  $profit = number_format( $price - $cost_price, 2, '.', '' );

  // replace tag in content with new value. note the brackets: {acf_profit}
  return str_replace( '{acf_profit}', $profit, $content ); 
}, 10, 3 );