Search code examples
phpwordpresswoocommerceproductorders

Adding custom message on WooCommerce thank you page based on product ID


I use the Plugin "Code Snippets" to put in the following codes in wordpress.

I changed the subtitle with the following code:

add_filter('woocommerce_thankyou_order_received_text', 'woo_change_order_received_text', 10, 2 );
function woo_change_order_received_text( $str, $order ) {
    $new_str = 'Deine Bestellung ist bei uns eingegangen und wird umgehend von uns bearbeitet.';
    return $new_str;
}

It worked pefectly, but I'd like to add a different text, when the customer buy a specific Product.

I found the following code:

<?php $present = false; ?>
<?php foreach( $order->get_items() as $item ):  
    $_product = wc_get_product( $item['product_id'] );
         // Add whatever product id you want below here
        if ( $item['product_id'] == 643 ):  
                $present = true; ?>

<?php endif; endforeach; ?>

<?php if( $present ): ?>

    <p class="woocommerce-notice woocommerce-notice--success woocommerce-thankyou-order-received"><?php echo apply_filters( 'woocommerce_thankyou_order_received_text', __( 'Thank you for buying this shirt', 'woocommerce' ), $order ); ?></p>
<?php else: ?>

    <p class="woocommerce-notice woocommerce-notice--success woocommerce-thankyou-order-received"><?php echo apply_filters( 'woocommerce_thankyou_order_received_text', __( 'Thank you. Your order has been received.', 'woocommerce' ), $order ); ?></p>
<?php endif; ?>

But it fails, when I add it into the functions.php of the theme or to the Plugin "Code snippets".


Solution

  • You can use the following, in this answer the product id = 30

    function filter_woocommerce_thankyou_order_received_text( $str, $order ) {
        // Get items
        $items = $order->get_items();
     
        foreach ( $items as $item ) {
            // Compare
            if ( $item->get_product_id() == 30 ) {
                $str = __( 'Deine Bestellung ist bei uns eingegangen und wird umgehend von uns bearbeitet.', 'woocommerce' );
                break;
            }
        }
        
        return $str;
    }
    add_filter( 'woocommerce_thankyou_order_received_text', 'filter_woocommerce_thankyou_order_received_text', 10, 2 );