基于可变产品和特定变量的 WooCommerce 结帐消息?

WooCommerce checkout message based for a variable product and a specific variable?

我添加了一条自定义消息,现在显示在 woocommerce_after_order_notes 下方,但我只想为产品的其中一个变量显示它。 以下代码仅针对主要产品显示 请告诉我如何为变量更改它。

add_action( 'woocommerce_after_order_notes', 'allclean_add_checkout_content', 12 );
function allclean_add_checkout_content() {
    // set your products IDs here:
    $product_ids = array( 91);
    $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>';
}

您可以像这样$cart_item['variation_id']查看购物车中是否有variation_id。试试下面的代码。

add_action( 'woocommerce_after_order_notes', 'allclean_add_checkout_content', 12 );
function allclean_add_checkout_content() {

    // set your products IDs here:
    $product_ids = array( 82, 94 ); // add your both product and variation id.

    $parent_ids_in_cart = false;
    
    foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
        $item = $cart_item['data'];
        if ( in_array( $item->id, $product_ids ) ){
            $parent_ids_in_cart = true;
        }
    }

    $variation_ids_in_cart = false;

    // Loop through cart items
    foreach( WC()->cart->get_cart() as $cart_item ) {
        // Collecting product variation IDs if they are in cart for this variable product
        if ( $cart_item['variation_id'] > 0 && in_array( $cart_item['variation_id'], $product_ids ) ){
            $variation_ids_in_cart = true;
        }
    }

    // It displays the message
    if ( $parent_ids_in_cart || $variation_ids_in_cart ){
        echo '<div class="checkoutdisc">This is Your custom message displayed.</div>';
    }

}