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.


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
    $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' );
  • 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

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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