Search code examples
phpwordpresswoocommercehook-woocommercepayment-method

Fatal error issue with woocommerce_thankyou hooked function


I need to print different messages based on payment method on the WooCommerce thank you page.

I am using the code below but it crashes my website and show me the following error:

Fatal error: Uncaught Error: Call to a member function get_payment_method() on int...

add_action( 'woocommerce_thankyou', 'bbloomer_add_content_thankyou' );
 
function bbloomer_add_content_thankyou($order) {
         if( 'bacs' == $order->get_payment_method() ) {

echo '<h2 class="h2thanks">Get 20% off</h2><p class="pthanks">Thank you for making this purchase! Come back and use the code "<strong>Back4More</strong>" to receive a 20% discount on your next purchase!</p>';
         }
    else{
        echo '<h2 class="h2thanks">Get 100% off</h2><p class="pthanks">Thank you for making this purchase! Come back and use the code "<strong>Back4More</strong>" to receive a 20% discount on your next purchase!</p>';

    }
    
}

Someone who can tell me where things are going wrong?


Solution

  • Via the woocommerce_thankyou hook you have access to the $order_id, not the $order object itself, hence the error.

    To obtain the $order object you can use wc_get_order( $order_id ); where by means of the $order_id the $order object is obtained.

    So you get:

    function bbloomer_add_content_thankyou( $order_id ) {    
        // Get $order object
        $order = wc_get_order( $order_id );
        
        // Is a WC_Order
        if ( is_a( $order, 'WC_Order' ) ) {
            // Payment method = bacs
            if( $order->get_payment_method() == 'bacs' ) {
                echo '<h2 class="h2thanks">Get 20% off</h2><p class="pthanks">Thank you for making this purchase! Come back and use the code "<strong>Back4More</strong>" to receive a 20% discount on your next purchase!</p>';
            } else {
                echo '<h2 class="h2thanks">Get 100% off</h2><p class="pthanks">Thank you for making this purchase! Come back and use the code "<strong>Back4More</strong>" to receive a 20% discount on your next purchase!</p>';
            }
        }
    }
    add_action( 'woocommerce_thankyou', 'bbloomer_add_content_thankyou', 10, 1 );