Search code examples
phpwoocommercepluginsmeasurement

Can I add a product using woocommerce measurement price calculator programmatically?


I am using the woocommerce measurement price calculator plugin to get prices using price grids. I am adding a product to my cart while already being on a product as this is an additional option.

My main goal is to get the price according to the price grid of that product.

It will use the same measurements as my main product since it is an option so I can pass these through, I am just not aware of how.

I know I can add a regular product to my cart via Ajax or in a different way in PHP by doing the following :

WC()->cart->add_to_cart($item['product_id'], $item_qty);

I can also get only the price of a product using the following :

$product = wc_get_product($product_id); 
return $product->get_price();

This works fine but I need to now get the price of a product that is using a price grid from the measurement plugin and I cannot figure out how to do this. The documentation doesn't seem to show me a way of retrieving a price from a price grid programmatically. Any help or ideas would be appreciated.


Solution

  • Thanks to the comment of LoicTheAztec I finally figured this out so I'm posting the answer here. Depending on what calculation we want to use for the price grid, the measurements and range checks can be adjusted. I just want to check one measurement against the high end of the range.

    Since the price grid is stored in the postmeta table with a meta key of '_wc_price_calculator_pricing_rules' we can get the price grid and then loop through each item until we find the rule that matches our measurements. We can then extract the price from that rule and use it in some way.

    $product = wc_get_product($id);
    $measurement_enabled = WC_Price_Calculator_Product::calculator_enabled( $product );
    
    if ($measurement_enabled) {
        $price_grid = $product->get_meta('_wc_price_calculator_pricing_rules');
        $measurements_total = 2000; // example value, i get mine from the cart_item_data
        $price_grid_price = 0;
    
        foreach ($price_grid as $grid_item) {
            if ($grid_item['range_end'] < $measurements_total) {
                $price_grid_price = $grid_item['price'];
            }
            else {
                break;
            }
        }
    
        return $price_grid_price;
    }