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


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.

    	$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.

  • 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

    $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)

The topic ‘WooCommerce price + ACF number field sum’ is closed to new replies.