WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have in my theme custom post types (products) with some meta-boxes. My client asked me, to automaticly give a unique SKU (meta-box) while saving that product.

My thought:

Give a random ID => have to check if that ID somewhere else exists OR

Give the Post-ID => that is just possible after saving once, cuz WP assign that ID while saving.

@Milo "additionally, a new post already has an ID before the user saves the post" How can I get the ID before I save the post and put it into that meta box and save it with a new post at once?


share|improve this question
Post IDs are already unique. Why is that not sufficient? – s_ha_dum Mar 17 '14 at 20:48
additionally, a new post already has an ID before the user saves the post. – Milo Mar 17 '14 at 20:50

When you add a meta box, the post object is passed to the function that outputs your meta box content, and the ID is immediately available. Here's a quick proof-of-concept that will put the ID in a field in a post meta box when creating a new post:

function wpd_sku_meta_box() {
add_action( 'add_meta_boxes', 'wpd_sku_meta_box' );

function wpd_render_meta_box( $post ) {
    // $post->ID contains the ID of newly created post:
    echo '<input type="text" id="wpd_sku" name="wpd_sku" value="' . $post->ID . '">';

function wpd_sku_save( $post_id ) {
    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) 
        return $post_id;

    if ( ! isset( $_POST['wpd_sku'] ) )
        return $post_id;

    $sku = $_POST['wpd_sku'];
    update_post_meta( $post_id, '_wpd_sku', $sku );
add_action( 'save_post', 'wpd_sku_save' );

but please don't use this code as-is, start with the example on the add_meta_box codex page, which has some nonce and permission checks.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.