如果购物车仅包含"Sold individually"件商品,则阻止WooCommerce结帐



我使用的是这段代码,因此用户可以(通过url(将具有自定义价格的产品添加到购物车中。这也使他们成为";单独销售";

add_filter( 'woocommerce_add_cart_item' , 'set_woo_prices');
add_filter( 'woocommerce_get_cart_item_from_session',  'set_session_prices', 20 , 3 );
function set_woo_prices( $woo_data ) {
if ( ! isset( $_GET['agcs'] ) || empty ( $_GET['agcs'] ) ) { return $woo_data; }
$woo_data['data']->set_price( $_GET['agcs'] );
$woo_data['data']->set_sold_individually('true');
$woo_data['my_price'] = $_GET['agcs'];

return $woo_data;
}
function  set_session_prices ( $woo_data , $values , $key ) {
if ( ! isset( $woo_data['my_price'] ) || empty ( $woo_data['my_price'] ) ) { return $woo_data; }
$woo_data['data']->set_price( $woo_data['my_price'] );
$woo_data['data']->set_sold_individually('true');
return $woo_data;
}

因为我用这个来追加销售我需要一张支票,如果购物车只包含";单独出售";项目

我过去常常用支票";如果购物车小于10美元,则取消结账";

add_action( 'woocommerce_check_cart_items', 'pokazimiga' );
function pokazimiga() {
if( is_cart() || is_checkout() ) {
global $woocommerce;
$minimum_cart_total = 9;
$total = WC()->cart->subtotal;



if( $total <= $minimum_cart_total  ) {
wc_add_notice( sprintf( '<strong>Nakup, manjši od %s %s ni mogoč</strong>'
.'<br />Trenutna vrednost košarice: %s %s',
$minimum_cart_total,
get_option( 'woocommerce_currency'),
$total,
get_option( 'woocommerce_currency') ),
'error' );
}
}
}

如果购物车中的所有商品都是set_sold_individually('true'),那么就足够了,然后不允许结账。

如果购物车只包含"单独出售";项目。

通过代码中添加的注释标签进行解释:

function action_woocommerce_check_cart_items() {
// Flag
$flag = false;

// Loop through cart items
foreach( WC()->cart->get_cart() as $cart_item ) {
// Cart contains an item that is not sold individually
if ( ! $cart_item['data']->get_sold_individually() ) {
// Flag becomes true
$flag = true;

// Break loop
break;
}
}

// When the flag is still false & the cart is NOT empty
if ( ! $flag && ! WC()->cart->is_empty() ) {
// Clear all other notices          
wc_clear_notices();
// Avoid checkout displaying an error notice
wc_add_notice( __( 'My custom error message', 'woocommerce' ), 'error' );

// Optional: remove proceed to checkout button
remove_action( 'woocommerce_proceed_to_checkout', 'woocommerce_button_proceed_to_checkout', 20 );   
}
}   
add_action( 'woocommerce_check_cart_items' , 'action_woocommerce_check_cart_items', 10, 0 );

最新更新