Reputation: 65
I am trying to manipulate the my_acf_save_post function to do some maths and update a field with the resulting number. This part is working, the fields full_market_price and example_price are used to work out calculated_price.
I did this some days ago but have now run in a problem whenever trying to save a page, or post that doesn't need this function, and doesn't contain the ACF fields. So every section of the website rather than just the 1 that requires this maths. It results in various errors and I can't save the pages properly.
How can I make this code snippet only work if the page being saved is within custom post type? So it won't break the other pages?
I'm trying something using
if (is_single() && is_post_type('nameofposttype'))
however I can't seem to get it right, PHP not my strongest! Is a better way to ask if the fields does not exist, then do nothing?
Many thanks for any help or ideas,
function my_acf_save_post( $post_id ) {
// get values
$fmp = get_field('full_market_price');
$saPercent = get_field('example_price');
// do something
$examplePrice = ($fmp / 100) * $saPercent;
update_field('calculated_price', $examplePrice, $post_id);
}
add_action('acf/save_post', 'my_acf_save_post', 20);
Upvotes: 3
Views: 2113
Reputation: 5511
I just ran into a similar issue. I would do something like:
function my_acf_save_post ($post_id) {
// If not CPT, exit
if (get_post_type($post_id) != 'nameofposttype') {
return;
}
// Remainder of code
...
}
add_action('acf/save_post', 'my_acf_save_post', 20);
Upvotes: 4