1 回答

TA貢獻(xiàn)1880條經(jīng)驗(yàn) 獲得超4個(gè)贊
以下代碼將根據(jù)產(chǎn)品 sku 對(duì)產(chǎn)品進(jìn)行最后排序
function sort_cart_specific_product_at_bottom( $cart ) {
// Product sku to to display at tbe bottom of the product list
$product_sku_last = array( 'lunchbox', 'pakket' );
// Set empty arrays
$products_in_cart = array();
$products_last = array();
$cart_contents = array();
// Loop through cart items
foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
// Get product sku
$product_sku = $cart_item['data']->get_sku();
// Get product id
$product_id = $cart_item['data']->get_id();
// In_array — checks if a value exists in an array
if ( in_array( $product_sku, $product_sku_last ) ) {
// Add to products last array
$products_last[ $cart_item_key ] = $product_id;
} else {
// Add to products in cart array
$products_in_cart[ $cart_item_key ] = $product_id;
}
}
// Merges the elements together so that the values of one are appended to the end of the previous one.
$products_in_cart = array_merge( $products_in_cart, $products_last );
// Assign sorted items to cart
foreach ( $products_in_cart as $cart_item_key => $product_id ) {
$cart_contents[ $cart_item_key ] = $cart->cart_contents[ $cart_item_key ];
}
// Cart contents
$cart->cart_contents = $cart_contents;
}
add_action( 'woocommerce_cart_loaded_from_session', 'sort_cart_specific_product_at_bottom', 10, 1 );
并且此代碼確保基于 sku 的商品不會(huì)從購(gòu)物車中移除
function prevent_cart_item_remove_link( $link, $cart_item_key ) {
// Product sku that should not be removable
$product_sku_last = array( 'lunchbox', 'pakket' );
if( WC()->cart->find_product_in_cart( $cart_item_key ) ) {
$cart_item = WC()->cart->cart_contents[ $cart_item_key ];
// Get product sku
$product_sku = $cart_item['data']->get_sku();
// In_array — checks if a value exists in an array
if ( in_array( $product_sku, $product_sku_last ) ) {
$link = '';
}
}
return $link;
}
add_filter( 'woocommerce_cart_item_remove_link', 'prevent_cart_item_remove_link', 10, 2 );
- 1 回答
- 0 關(guān)注
- 84 瀏覽
添加回答
舉報(bào)