Search code examples
phpwordpresswoocommercewordpress-rest-api

Creating a customer price in woocommerce via API


I have found a plugin that creates customer specific pricing, but seems to be an external API call that seem to not be the solution I am looking for.

https://woocommerce.com/products/wisdm-customer-specific-pricing/

I was confused to how the cart works and how products are stored. But based on this post it showed me how to replace cart prices with customer ID and sku's being passed to the API.

I used this this ticket to start off my answer

So the big thing I needed to figure out is how to call the cart, loop through each product and grab it's product SKU then overwrite the price.


Solution

  • I added the following to my functions.php in my theme to change my cart to display the correct pricing based off of my customer API pricing. This does a loop through all my cart items then make a call to the API and returns a price for the specific customer and sku.

    add_action( 'woocommerce_before_calculate_totals', 'add_custom_price' );
    
    function add_custom_price( $cart_object ) {
        foreach ( $cart_object->cart_contents as $key => $value ) {
             $response = get_api_response($value['data']->get_sku(), $customer_id);
             $custom_price = $response->price;
    
             $value['data']->set_price($custom_price);
        }
    }