I’m working with extra postmeta – invoice number for orders which use bacs as a payment method. I have added a invoice number to orders in Woocommerce by using this:

global $wpdb;

$orders = get_posts( array(
    'post_type'   => 'shop_order',
    'posts_per_page' => '-1',
    'meta_key'  =>  '_payment_method',
    'meta_value'    =>  'bacs',
    'orderby'   => 'post_date',
    'order' => 'ASC'
));

$counter = 1001;

foreach($orders as $order) {
    update_post_meta($order->ID, '_billing_invoice_number', $counter++);
}

So the last invoice number I got on my test site is 1006. Now I want to increase this number by 1 when the new order is added to the store. Here is my code which I’m trying to use

add_action('woocommerce_checkout_update_order_meta', 'my_custom_checkout_field_update_order_meta' );

function my_custom_checkout_field_update_order_meta( $order_id ) {
$order = new WC_Order($order_id);

global $wpdb;

$last_order = get_posts( array(
    'post_type'   => 'shop_order',
    'posts_per_page' => '1',
    'meta_key'  =>  '_payment_method',
    'meta_value'    =>  'bacs',
    'orderby'   => 'post_date',
    'order' =>  'DESC'
));

$last = $last_order[0]->ID;
$test = get_post_meta($last, '_billing_invoice_number');
$final = $test[0] + 1;

if($_POST['payment_method'] == 'bacs') {
    update_post_meta( $order_id, '_billing_invoice_number', (string)$final);
}

}

The value saved in order is 1. I tried to save only $test[0] but I got empty postmeta value. I checked also if I’m getting the ID of the last order and it is stored successfully when I save $last as postmeta value.

What can be a problem here? I tried it code on the separate file (test.php) and the value I get from $test[0] is

/var/www/wordpress/test-site/wp-content/themes/myTheme/test.php:19:string '1006' (length=4)

Read more here: Get postmeta of last order, increase it by 1 and add to new order


Solution:

If you know the solution of this issue, please leave us a reply in Comment section, to update the question.


Wordpress related questions and answers: