-3

I follow the solution of this post to get the custom price from the input field with a cookie and it works properly except mini-cart.

My products are added to the cart with AJAX and the mini-cart doesn't load the new value of the cookie. It seems to be cached to the previous value of the input field until you reach to the cart page and after hard reload.

For example, I visit the page where I enter the custom price. The first time I put 20 euros, I press the add to cart button, my product is added to the cart via AJAX and it works well. If I remove this product with the custom price and try to add it again with a different price at this time, the mini-cart keeps the previous price(20 euros).

So, the question is if there is a way to keep the mini-cart updated with the last inserted price?

GeorgeA
  • 1
  • 1

1 Answers1

0

Gratuitous self-promotion, but my Name Your Price should automatically work with the mini-cart.

But I think your question is actually asking why the item isn't being considered as unique... and therefore added a second time. The answer is that a different price will render a unique $cart_id see source. With a unique ID the item is not found in the cart, and so it is added again.

To force a 'sold individually' item with different prices to be truly sold individually, you need to change the way the cart ID is generated, by filtering woocommerce_cart_id. Here is how I do it to work with my Name Your Price plugin. You would need to adapt it to your own code.

<?php
/**
 * Plugin Name: WooCommerce Name Your Price Sold Individually
 * Plugin URI: https://gist.github.com/helgatheviking/a8802255167751a5dd746f83cdfc8716
 * Description: Double check enforcement of "Sold Individually" for NYP items
 * Version: 1.1.0
 * WC requires at least: 2.6.3   
 * Author: Kathy Darling
 * Author URI: http://kathyisawesome.com/
 *
 * Copyright: © 2016 Kathy Darling
 * License: GNU General Public License v3.0
 * License URI: http://www.gnu.org/licenses/gpl-3.0.html
 */

function wc_nyp_force_sold_individually( $cart_id, $product_id, $variation_id, $variation, $cart_item_data ) {
    // Get the product
    $product = wc_get_product( $variation_id ? $variation_id : $product_id );
    if ( $product->is_sold_individually() && WC_Name_Your_Price_Helpers::is_nyp($product) ){
        $id_parts = array( $product_id );
        if ( $variation_id && 0 != $variation_id ) {
            $id_parts[] = $variation_id;
        }
        if ( is_array( $variation ) && ! empty( $variation ) ) {
            $variation_key = '';
            foreach ( $variation as $key => $value ) {
                $variation_key .= trim( $key ) . trim( $value );
            }
            $id_parts[] = $variation_key;
        }
        $cart_id = md5( implode( '_', $id_parts ) );
    }
    return $cart_id;
}
add_filter( 'woocommerce_cart_id', 'wc_nyp_force_sold_individually', 10, 5 );
helgatheviking
  • 25,596
  • 11
  • 95
  • 152