Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save gitSambhal/3ef1ab88f657491ba5ebaf87317aed97 to your computer and use it in GitHub Desktop.
Save gitSambhal/3ef1ab88f657491ba5ebaf87317aed97 to your computer and use it in GitHub Desktop.
Ramdom invoice number in woocommerce using WooCommerce Print Invoice & Delivery Note plugin.
<?php
//woocommerce-delivery-notes/includes/class-wcdn-print.php
public function get_order_invoice_number( $order_id ) {
// Custom random invoice no
$invoice_count = mt_rand(1,9999);
$invoice_prefix = mt_rand(1,9999);
$invoice_suffix = mt_rand(1,99999);
// Check if this invoice no is already exists, if exists then create new invoice no
$custom_invoice_no = $invoice_prefix .'-'. $invoice_count .'-'. $invoice_suffix;
// Add the invoice number to the order when it doesn't yet exist
$meta_key = '_wcdn_invoice_number';
//Check if any order exists with this invoice id
$args = array(
'post_type' => 'shop_order',
'meta_query' => array(
array(
'key' => '_wcdn_invoice_number',
'value' => $custom_invoice_no
)
)
);
$my_query = new WP_Query( $args );
while( !empty($my_query->have_posts()) ) {
// Order exists create new invoice id
$invoice_count = mt_rand(1,9999);
$invoice_prefix = mt_rand(1,9999);
$invoice_suffix = mt_rand(1,99999);
$custom_invoice_no = $invoice_prefix .'-'. $invoice_count .'-'. $invoice_suffix;
$args = array(
'post_type' => 'shop_order',
'meta_query' => array(
array(
'key' => '_wcdn_invoice_number',
'value' => $custom_invoice_no
)
)
);
$my_query = new WP_Query( $args );
}
$meta_added = add_post_meta( $order_id, $meta_key, $custom_invoice_no, true );
// Update the total count
if( $meta_added ) {
update_option( 'wcdn_invoice_number_count', $invoice_count + 1 );
}
// Get the invoice number
return apply_filters( 'wcdn_order_invoice_number', get_post_meta( $order_id, $meta_key, true ) );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment