如果陳述句為真(產品 id 存在于陣列中),我正在嘗試運行一個函式,我想從中排除特定的產品 id。
到目前為止,我有以下代碼可以正常作業,但它仍然適用于所有產品,請問我該如何排除這個產品?
if ( ! is_null( WC()->cart ) ) {
// Initialize
$product_ids = array();
// Loop through cart contents
foreach ( WC()->cart->get_cart_contents() as $cart_item ) {
if ($cart_item['product_id'] != 32) {
// Get product ID and push to array
$product_ids[] = $cart_item['variation_id'] > 0 ? $cart_item['variation_id'] : $cart_item['product_id'];
}
}
}
uj5u.com熱心網友回復:
您的代碼本身沒有問題,但是您$cart_item['product_id']
在 if 條件下使用,所以如果它是一個變體 ID,您的條件將不會得到滿足。
可以使用 if 條件,但是將其應用于 1 個或多個產品 ID,您最好使用 NOT ( !
) in_array()
所以你得到:
if ( ! is_null( WC()->cart ) ) {
// Initialize
$product_ids = array();
// Loop through cart contents
foreach ( WC()->cart->get_cart_contents() as $cart_item ) {
// Get product ID
$product_id = $cart_item['variation_id'] > 0 ? $cart_item['variation_id'] : $cart_item['product_id'];
// Exlude Product ID(s), NOT in array
if ( ! in_array( $product_id, array( 32, 30, 817 ) ) ) {
// Push to array
$product_ids[] = $product_id;
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/432573.html
標籤:WordPress woocommerce 产品 大车