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.
first of all, are you using it within a simple text field or a rich text field?
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}' )
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;
}
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 );