Home › Forums › General Issues › Custom field to change Cart Price › Reply To: Custom field to change Cart Price
My end goal is to be able to use a custom price for specified customers. I’ve figured that part out and the alter_price
function is working. the hard part, making that translate into the cart is where I’m struggling – it seems to be a different ball game.
function alter_price( $price ) {
$customer = get_field('customer',$product->id);
$special_customer_ids = [$customer];
if ( in_array( get_current_user_id(), $special_customer_ids, true ) && (get_field('special_price',$product->id))) {
$price = get_field('special_price');
return $price;
} else {
return $price;
}
}
add_filter( 'woocommerce_product_get_price', 'alter_price', 10, 1 );
add_action( 'woocommerce_before_calculate_totals', 'add_custom_price', 20, 1);
function add_custom_price( $cart_obj ) {
// This is necessary for WC 3.0+
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// Avoiding hook repetition (when using price calculations for example)
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
// Loop through cart items
foreach ( $cart_obj->get_cart() as $cart_item ) {
$customer = get_field('customer',$product->id);
$special_customer_ids = [$customer];
if ( in_array( get_current_user_id(), $special_customer_ids, true ) && (get_field('special_price',$product->id))) {
$newprice = get_field('special_price');
$cart_item['data']->set_price( $newprice );
}
}
}
I have been looking all over the place and been through several alterations of add_custom_price
. I think I should probably be using the_field
and a product ID. Any help is appreciated.
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
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 Privacy Policy. If you continue to use this site, you consent to our use of cookies.