根据 WooCommerce 产品自定义库存状态禁用添加到购物车按钮

Disable add to cart button based on WooCommerce product custom stock status

目前在 woocommerce 中,如果库存状态为 out of stock,添加到购物车按钮已禁用。我使用 woocommerce_product_stock_status_options 添加带有标签 Discontinued product 的新库存状态,现在我正在寻找一种方法来处理此产品,就像它缺货一样。

因为我认为最好将不再生产的产品与在另一家商店生产并有售但没有库存的产品分开。

您可以使用以下方法根据自定义库存状态禁用“添加到购物车”按钮 (您将用自定义状态块替换 custom_status_slug

add_filter('woocommerce_is_purchasable', 'filter_is_purchasable_callback', 10, 2 );
add_filter('woocommerce_variation_is_purchasable', 'filter_is_purchasable_callback', 10, 2 );
function filter_is_purchasable_callback( $purchasable, $product ) {
    if ( $product->get_stock_status() === 'custom_status_slug' ) {
        return false;
    }

    return $purchasable;
}

代码进入活动子主题(或活动主题)的 functions.php 文件。已测试并有效。

我提出一个解决方案,在产品页面上显示库存状态,而不是 'add to cart' 按钮

add_filter('woocommerce_product_is_in_stock', 'filter_is_in_stock_callback', 10, 2 );
function filter_is_in_stock_callback( $stock, $product ) {
    if ( $product->get_stock_status() === 'custom_status_slug' ) {
        return false;       
    }
    return $stock;
}

感谢第一个回答:)