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

时间:2018-11-02 11:00:13

标签: php wordpress woocommerce product orders

我在woocommerce Thankyou.php中获得了以下代码,如果仅购买了ONE类别的产品,此方法将起作用。当购买“电子书”和“机票”类别的产品时,“机票”将添加到$ 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>;
     ?>

1 个答案:

答案 0 :(得分:1)

请尝试以下操作,该操作会将您的产品名称存储在数组中,删除重复的值并在消息中显示产品名称:

// 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")
);

经测试可正常工作