在 Woocommerce 中显示基于自定义文本的产品类别订单项目名称谢谢

Display a custom text based product category order item names in Woocommerce thankyou

我在我的 woocommerce thankyou.php 中得到了以下代码,如果只购买了一个类别的产品,则此代码有效。当同时购买 'ebook' 和 'ticket' 类别的产品时,'ticket' 将添加到 $productname 变量中。

如何判断列表中的商品属于一类还是多类?

    <?php 
        $email = $order->billing_email;
        $order_info = wc_get_order( $order );
        $productname = "";

        foreach( $order_info->get_items() as $item ) {
            // check if a product is in specific category
            if ( has_term( 'ebook', 'product_cat', $item['product_id'] ) ) {
                $productname = ' ebook';
            } elseif (has_term( 'ticket', 'product_cat', $item['product_id'] )) {
                $productname = 'ticket';
            } else {
                $productname = 'order details';
            }           

        }

        echo '<p> Your ' . $productname . ' will be send to <strong>' . $email . '</strong> as soon as the payment is received.<br>;
     ?>

尝试以下方法,将您的产品名称存储在一个数组中,删除重复值并在消息中显示产品名称:

// Get the instance of the WC_Order Object from the $order_id variable
$order = wc_get_order( $order_id );

$product_names = array(); // Initializing

// Loop through order items
foreach( $order->get_items() as $item ) {
    // check if a product is in specific category
    if ( has_term( 'ebook', 'product_cat', $item['product_id'] ) )
    {
        $product_names[] = '"Ebook"';
    }
    elseif ( has_term( 'ticket', 'product_cat', $item['product_id'] ) )
    {
        $product_names[] = '"Ticket"';
    }
    else
    {
        $product_names[] = '"Others"';
    }
}
$product_names = array_unique( $product_names );


echo sprintf( '<p>%s %s %s <strong>%s</strong> %s</p><br>',
    _n( "Your", "Yours", sizeof( $product_names ), "woocommerce-bookings" ),
    implode( ', ', $product_names ),
    __("will be sent to", "woocommerce-bookings"),
    $order->get_billing_email(),
    __("as soon as the payment is received.", "woocommerce-bookings")
);

已测试并有效