0

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

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

1 Answer 1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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