基于特定产品类别的 WooCommerce 结帐消息

WooCommerce checkout message based on specific product category

Wordpress 商店正在使用 WooCommerce,我有一个小的购买记录,我需要出现在 WooCommerce Checkout 上,但只有在购买特定产品时才会出现。

我添加了一条自定义消息,该消息现在显示在“下订单”按钮下方。 然而,无论购物车中有什么,它都会出现。

这是我目前使用的代码:

add_action( 'woocommerce_after_checkout_form', 'allclean_add_checkout_content', 12 );
function allclean_add_checkout_content() {
echo '<div class="checkoutdisc">Custom message appears here fine.</div>';
}

我可以在此行之前添加一个简单的代码,使其仅在特定类别产品在购物车中时适用吗?

谢谢

我认为您需要检查一下购物车中的物品。

add_action( 'woocommerce_after_checkout_form', 'allclean_add_checkout_content', 12 );
function allclean_add_checkout_content() {
    $cart = WC()->cart;
    foreach ( $this->get_cart() as $cart_item_key => $values ) {
        $_product = $values['data'];

        if ( has_term( 'special-category', 'product_cat', $_product->id ) ){
            echo '<div class="checkoutdisc">Your custom message.</div>';
        }
    }
}

Here we check that we have a product item in cart with this special category. If the condition is matched (in one of the items of the cart), the message is displayed.

代码如下:

add_action( 'woocommerce_after_checkout_form', 'allclean_add_checkout_content', 12 );
function allclean_add_checkout_content() {
    // set your special category name, slug or ID here:
    $special_cat = 'special_category';
    $bool = false;
    foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
        $item = $cart_item['data'];
        if ( has_term( $special_cat, 'product_cat', $item->id ) )
            $bool = true;
    }
    // If the special cat is detected in one items of the cart
    // It displays the message
    if ($bool)
        echo '<div class="checkoutdisc">This is Your custom message displayed.</div>';
}

You can also use an array of products Ids instead of a product category...

在这种情况下,代码会有点不同:

add_action( 'woocommerce_after_checkout_form', 'allclean_add_checkout_content', 12 );
function allclean_add_checkout_content() {
    // set your products IDs here:
    $product_ids = array( 31, 68, 87, 124);
    $bool = false;
    foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
        $item = $cart_item['data'];
        if ( in_array( $item->id, $product_ids ) )
            $bool = true;
    }
    // If the special cat is detected in one items of the cart
    // It displays the message
    if ($bool)
        echo '<div class="checkoutdisc">This is Your custom message displayed.</div>';
}

此代码进入您的活动子主题(或主题)的 function.php 文件或任何插件文件

此代码已经过测试并且有效。