0

I have two ACF fields named as “price” and “reduced_price” now i have another field named as “price_filter” which should be filled with following conditions,

  • If “price” is greater than “reduced_price” and “reduced_price” is not empty then “price_filter” = “reduced_price”
  • If “price” is 0 or “price” is empty then “price_filter” = 0
  • Else “price_filter” = “price”

Now everything was working fine but when I put “price = 117900” and “reduced_price = 99900” It should fulfill the first condition and display “price_filter” = “reduced_price” but its not working like that and showing “price_filter” = “price”

Here is my PHP code

function my_acf_save_post( $post_id ) {
$price = get_field(‘price’);
$reduced_price = get_field(‘reduced_price’);

if ($price > $reduced_price && !empty($reduced_price)) {
update_field(‘price_filter’, $reduced_price);
}
else if($price == “0” || empty($price)) {
update_field(‘price_filter’, ‘0’);
}
else {
update_field(‘price_filter’, $price);
}
}
add_action(‘acf/save_post’, ‘my_acf_save_post’, 20);
1
  • is this your actual code? It looks like you're using smart apostrophes and commas etc. You need to make sure they are all straight. ‘ vs '
    – rudtek
    Commented May 22, 2023 at 21:59

1 Answer 1

0

Due to the ‘ vs ' that was already mentioned and since your code logic is correct, I suggest you make sure you're comparing integers, not strings. PHP can be surprising when working with strings as numbers, so cast them as int. Also, make sure you're getting the correct values by adding $post_id, like this:

$price = intval(get_field('price', $post_id));

$reduced_price = intval(get_field('reduced_price', $post_id));

"117900" is considered smaller than "99900" as strings. PHP will compare ASCII values of the first character from the string - "1" vs "9" in our case. If the first character from the first string is smaller, the whole first string is smaller. If they're equal, it moves on to the next character, an so on.

1
  • Note that if the prices have decimals, then use floatval() rather than intval().
    – Caleb
    Commented May 31, 2023 at 16:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.