Add a pay order button on WooCommerce My account view order for pending orders

How create “pay for this order” button when order status is pending to be displayed on the my account page when viewing an order

The link structure is as follows:

https://url.com/checkout/order-pay/XXXXX/?pay_for_order=true&key=wc_order_XXXXXXXXXXXX

add_action( 'woocommerce_view_order', 'order_pay_button' );
function order_pay_button( $order_id ){
// Get an instance of the `WC_Order` Object
$order = wc_get_order( $order_id );

// Get the order number
$order_number  = $order->get_order_number();

    
// Get the order status name
$status_name  = wc_get_order_status_name( $order->get_status() );

// Get the order key
 $test_order_key = $order->get_order_key();
 
   
// Display the order status 
echo '<div>' . __("Order Status:") . ' ' . $status_name . '</div>';



if ($status_name == "pending") {
   
     echo '
<a href="https://url.com/checkout/order-pay/'.''.$order_number.''.'/?pay_for_order=true&key='.''.$test_order_key.''.'">
<button type="submit" class="button alt" id="place_order">Pay for this order</button></a>';
   
} 


}

Answer

Try the following simplified code version, that will display a pay order button for pending orders:

add_action( 'woocommerce_view_order', 'order_pay_button' );
function order_pay_button( $order_id ){
    // Get an instance of the `WC_Order` Object
    $order = wc_get_order( $order_id );

    if ( $order->get_status() == "pending" ) {
        printf(
            '<a class="woocommerce-button button pay" href="%s/order-pay/%s/?pay_for_order=true&key=%s">%s</a>',
            wc_get_checkout_url(), $order_id, $order->get_order_key(), __("Pay for this order", "woocommerce")
        );
    }
}

Code goes in functions.php file of the active child theme (or active theme). Tested and works.

Leave a Reply

Your email address will not be published. Required fields are marked *