如果产品已经在 WooCommerce 购物车中,则禁用添加到购物车按钮

Disable add to cart button if product is already in WooCommerce cart

如果产品已添加,我想禁用 'add to cart' 按钮。我已经设法改变了。测试已添加的产品,以便它为按钮显示 'Already added'。代码或那个在下面。除了文本更改之外,我只是不知道如何禁用该按钮。

add_filter('woocommerce_product_add_to_cart_text', 'wc_product_add_to_cart_text', 10, 2 );
add_filter('woocommerce_product_single_add_to_cart_text', 'wc_product_add_to_cart_text', 10, 2 );

function wc_product_add_to_cart_text( $text, $product ){

    $product_cart_id = WC()->cart->generate_cart_id( $product->get_id() );
    $in_cart = WC()->cart->find_product_in_cart( $product_cart_id );

    if ( $in_cart ) {
        $text = "Already added";
    }
    return $text;
}

当您在 WooCommerce 中编辑产品时,可以 select“仅单独销售”。我不知道这是否是您想要实现的目标,但这可能是更合适的解决方案,而且更不容易出现错误。

如果您根本不使用默认的商店页面,您应该在商店页面放置一个重定向,该重定向总是将用户重定向到例如您用于商店的页面。

除此之外, 您会找到一个挂钩,可用于禁用“添加到购物车”的重定向。

我找到这个代码来检查产品是否已经在您的购物车中。您可以从 body_class(); 获取当前产品 ID。只需将此函数挂接到 woocommerce_add_to_cart.

function woo_in_cart($product_id) {
    global $woocommerce;         
    foreach($woocommerce->cart->get_cart() as $key => $val ) {
        $_product = $val['data'];

        if($product_id == $_product->id ) {
            wp_redirect( $url );
        }
    }         
}