我正在尝试编写一个隐藏商店页面特定产品的钩子,如果它在购物车中,但我似乎无法弄清楚两件事。
function find_product_in_cart() {
$hide_if_in_cart = array(6121, 6107, 14202, 14203);
$in_cart = false;
foreach( WC()->cart->get_cart() as $cart_item ) {
$product_in_cart = $cart_item['product_id'];
foreach ( $hide_if_in_cart as $key => $value ) {
if ( $product_in_cart === $value ) {
$in_cart = true;
}
}
if ( $in_cart ) {
echo 'Product in cart';
} else {
echo 'Not in cart!';
}
}
}
add_action('woocommerce_before_shop_loop_item', 'find_product_in_cart
这是目前的输出: https://i.gyazo.com/d85bd93598ada7aa96bee9a1d7393c3c.png
答案 0 :(得分:1)
以下代码将使用此专用的Woocommerce操作挂钩从Woocommerce商店和存档页面中删除特定的定义产品:
add_action( 'woocommerce_product_query', 'hide_specific_products_from_shop', 20, 2 );
function hide_specific_products_from_shop( $q, $query ) {
if( is_admin() && WC()->cart->is_empty() )
return;
// HERE Set the product IDs in the array
$targeted_ids = array( 6121, 6107, 14202, 14203 );
$products_in_cart = array();
// Loop through cart items
foreach( WC()->cart->get_cart() as $cart_item ){
if( in_array( $cart_item['product_id'], $targeted_ids ) ){
// When any defined product is found we add it to an array
$products_in_cart[] = $cart_item['product_id'];
}
}
// We remove the matched products from woocommerce lopp
if( count( $products_in_cart ) > 0){
$q->set( 'post__not_in', $products_in_cart );
}
}
代码进入活动子主题(或活动主题)的function.php文件。经过测试并正常工作。