Auto Populate Custom Field with Complex Value That Increase by One?

Can somebody help me to sort this?

I am using WP 3.5.2 and I have “Orders” post type where purchase_order custom field is located.

Read More

This is the sample of purchase order record:

POCOS20130051

PO – is prefix that is always the same

CO – first 2 letters of the site name – if site name is “Coca Cola” – CO will appear (if I change the name of the site, this will change too)

S – always the same

2013 – current year

0051 – number that increase by 1 when hit Add New Order. Must have 4 characters. If number is 1 then 0001 will appear.

Now….

I need this as a hook that will auto generate and auto populate my purchase_order custom filed.
PO number must be generated as a unique record.

Function has to count “published and drafted” Order post types and then to increase that number by one, so last part of PO number can be generated (0051).

For the reference, please take a look how this guy solved something similar
http://www.codeproject.com/Articles/491733/Auto-generated-sequence-number-in-SQL-Server

Thanks.

Related posts

1 comment

  1. I suppose you need somewhere to globally store last order number. Preferable in table wp_options. Method update_option will help you.
    Then you need to make a function which will fires everytime when new order appears.

    something like that:

    add_action( 'save_post', 'setOrderNumber');
    function setOrderNumber($post_id) {
    
      $slug = 'orders'; // slug of your post_type called "Orders"
    
      if ( $slug != $_POST['post_type'] ) {
            return;
        }
      if ( !current_user_can( 'edit_post', $post_id ) ) {
            return;
        }
    
      $counter = get_option( 'lastOrderCount' ); // example 0051
      $counter++; // returns 0052
      update_post_meta($post_id, 'purchase_order', 'POCOS'.date('Y').$counter);
      update_option( 'lastOrderCount', $counter ); // set the new number of order. 
    }
    

    I didn’t checked this function, but I hope it works.

Comments are closed.