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 want to save multiple custom fields for a custom post in one go. Something like get_post_custom() except for that I need to set it this time.

share|improve this question

1 Answer 1

Custom post meta data are generally updated in the database via a callback function hooked into save_post. (Others: draft_post, publish_post, future_post.)

The custom post meta data are part of the $_POST data sent on-submit for the edit post screen, so simply look for them there, sanitize them, and then update them in the database.

I'm omitting things like nonce-checking and sanitizing $_POST data. You'll want to incorporate them into your callback as necessary.

For example:

function wpse63622_save_custom_post_metadata() {
    // Globalize $post
    global $post;

    // Find custom post meta data in $_POST
    // DON'T FORGET TO SANITIZE
    $custom_post_meta_1 = ( isset( $_POST['_custom_meta_key_1'] ) ? $_POST['_custom_meta_key_1'] : false );
    $custom_post_meta_2 = ( isset( $_POST['_custom_meta_key_2'] ) ? $_POST['_custom_meta_key_2'] : false );
    $custom_post_meta_3 = ( isset( $_POST['_custom_meta_key_3'] ) ? $_POST['_custom_meta_key_3'] : false );

    // Update the database
    if ( $custom_post_meta_1 ) {
        update_post_meta( $post->ID, '_custom_meta_key_1', $custom_post_meta_1 );
    }
    if ( $custom_post_meta_2 ) {
        update_post_meta( $post->ID, '_custom_meta_key_2', $custom_post_meta_2 );
    }
    if ( $custom_post_meta_3 ) {
        update_post_meta( $post->ID, '_custom_meta_key_3', $custom_post_meta_3 );
    }
}
add_action( 'save_post', 'wpse63622_save_custom_post_metadata' );
add_action( 'publish_post', 'wpse63622_save_custom_post_metadata' );
share|improve this answer
    
Does every update_post_meta() query the database each time? –  Poulomi Nag Aug 30 '12 at 14:47
    
Coz my site is going to be heavy and I am optimizing and reducing unnecessary querying. So I was wondering if I could somehow put all the meta key-value pairs in an array and then update thw whole thing together. Is there a way to achieve this? –  Poulomi Nag Aug 30 '12 at 15:05
    
"Does every update_post_meta() query the database each time?" - Each time what? –  Chip Bennett Aug 30 '12 at 15:35
    
Does it save the meta value to the database and come back at every execution of the function? –  Poulomi Nag Aug 30 '12 at 15:57
    
Yes, every time you save or publish that post, the post custom meta data will be updated. Just like all of the rest of the data for the $post object. –  Chip Bennett Aug 30 '12 at 15:58

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.