Support

Account

Home Forums Front-end Issues WooCommerce price + ACF number field sum

Solved

WooCommerce price + ACF number field sum

  • I’m trying to change WooCommerce price based on an ACF number field.
    My problem is that the sum of ACF number field + Product Price isn’t right.

    <?php
    	$price_html = $product->get_price();
    	$x = get_field('custom-price');
    	$finalPrice = ($x + $price_html);
    	echo $finalPrice;
    	?>

    The value of ACF number field is 1,265 and the price of product is 5.
    The sum I get is 6 instead of 6,125.
    I tried to change the value to ACF field to 1.265 but i got the same result.

    • RemSEO

    • October 11, 2019 at 11:12 pm

    Hi,

    The ACF number field will return an integer.
    In php you’ll never have some decimal with an integer value, you have to work with float values.

    Maybe you could simply try something like this

    <?php
    $price_html = $product->get_price(); //It will return a string
    $x = get_field(‘custom-price’); //Integer
    $float_price = floatval($price_html); //Float
    $float_custom_price = floatval($x); //Float
    $finalPrice = ($float_price + $float_custom_price); //Float
    echo $finalPrice;
    ?>

    But this will only display your custom price.
    If you want to actually modify your price you have to use woocommerce filters.
    In product page :

    // Simple, grouped and external products
    add_filter(‘woocommerce_product_get_price’, ‘custom_price’, 99, 2 );
    add_filter(‘woocommerce_product_get_regular_price’, ‘custom_price’, 99, 2 );
    // Variations
    add_filter(‘woocommerce_product_variation_get_regular_price’, ‘custom_price’, 99, 2 );
    add_filter(‘woocommerce_product_variation_get_price’, ‘custom_price’, 99, 2 );

Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.

We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Cookie Policy. If you continue to use this site, you consent to our use of cookies.