如果购物车中有商品,请从循环中隐藏特定的Woocommerce产品 [英] Hide a specific Woocommerce products from loop if they are in cart

查看:74
本文介绍了如果购物车中有商品,请从循环中隐藏特定的Woocommerce产品的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个钩子,如果购物车中有特定产品,该钩子会将其隐藏在商店页面中,但是我似乎无法弄清楚两件事。

I'm trying to write a hook that hides a specific product from the shop page if it's in the cart, but I can't seem to figure out two things.

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




  1. 代码到处都打印出购物车中的产品,因为购物车中有一个ID为 14202的产品。我的逻辑在某处是错误的...

  2. 我不知道如何隐藏单个产品,现在我打印一行文本,但我希望能够显示:无;它;或者使用特定功能

当前的输出是:
https://i.gyazo.com/d85bd93598ada7aa96bee9a1d7393c3c.png

推荐答案

以下代码将使用此专用Woocommerce动作挂钩从Woocommerce商店和存档页面中删除特定定义的产品,当它们在购物车中时:

The following code will remove a specific defined products from Woocommerce shop and archive pages when they are in cart, using this dedicated Woocommerce action hook:

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文件您的活动子主题(或活动主题)。经过测试并有效。

这篇关于如果购物车中有商品,请从循环中隐藏特定的Woocommerce产品的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆