daniyalahmad
daniyalahmad

Reputation: 3843

Get a previous order number WooCommerce

I am trying to get previous order number from the specified order number for example there are 5 orders we have. 1780 1781 1782 1784 1786 Now if i specifiy the order number

wc_custom_get_previous_order_number(1784)

I should get 1782. I have tried multiple solutions. For example :

add_filter( 'woocommerce_order_number', 'custom_woocommerce_order_number', 1, 2 );
function custom_woocommerce_order_number( $oldnumber, $order ) {
  $lastorderid = $order->id-1; // here is i am trying to get previous order number.
// other code...
}

Upvotes: 1

Views: 435

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 253814

You could build your own function with a SQL query with 2 arguments:

  • $order_id is the starting order ID.
  • $limit is the number of orders Ids to get from.

The function code:

function get_orders_from( $order_id, $limit = 1 ){
   global $wpdb;

    // The SQL query
    $results = $wpdb->get_col( "
        SELECT ID
        FROM {$wpdb->prefix}posts
        WHERE post_type LIKE 'shop_order'
        AND ID < $order_id
        ORDER BY ID DESC
        LIMIT $limit
    " );
    return $limit == 1 ? reset( $results ) : $results;
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.


USAGE (examples):

1) To get the previous order ID from the current $order_id you will use in your code:

$previous_order_id = get_orders_from( $order_id );

You will get directly the previous order ID…

2) To get the 3 previous orders IDs from order ID 1784:

// Get the array of orders_ids
$orders_ids = get_orders_from( 1784, 3 );

// Converting and displaying a string of IDs (coma separated)
echo implode( ', ', $orders_ids );

You will get: 1780, 1781, 1782

Upvotes: 1

Related Questions