Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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?

Thanks

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

1 Answer 1

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_meta_box(
        'wpd_sku',
        'SKU',
        'wpd_render_meta_box',
        'post'
    );
}
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

 
discard

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.