Fjott
Fjott

Reputation: 1137

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

I got the following code in my woocommerce thankyou.php, this works if only products from ONE category is bought. When products from both the 'ebook' and the 'ticket' category are bought, 'ticket' will be added to the $productname variable.

How to determine if the products in the list are of one or multiple categories?

    <?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>;
     ?>

Upvotes: 1

Views: 332

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 254373

Try the following instead that will store your product names in an array, removing duplicated value and displaying the product names in your message:

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

Tested and works

Upvotes: 1

Related Questions