how to save multiple custom fields for a post in one go?

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.

Related posts

Leave a Reply

1 comment

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