Change 2 fields in the post depending on the 3rd field before save

Use the hook save_post and put an if inside the function that do the save after the ‘normal’ save meta fields routine.

add_action( 'save_post', 'this_is_the_function_name' ); 

function this_is_the_function_name( $post_id ) { 

    // No auto saves 
    if( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return; 

    // make sure the current user can edit the post 
    if( ! current_user_can( 'edit_post' ) ) return;

    // assure the post type
    if ( ! get_post_type($post_id) == 'cards' ) return;

    // assure the data are sended by the form
    if (
       ! isset($_POST['my_cards_activity']) ||
       ! isset($_POST['my_cards_datetime']) || ! isset('my_cards_user')
    ) return;

    $activity = $_POST['my_cards_activity'];

    // and now the simply logic
    if ( $activity == 1 ) {
        $datetime = $_POST['my_cards_datetime'];
        $user = $_POST['my_cards_user'];
    } else {
        $datetime="";
        $user="";    
    }

    // save data as array
    $meta_data = compact("activity", "datetime", "user");
    update_post_meta($post_id, 'card_data', $meta_data);

    // if you want can save data as 3 different meta fields in this case
    // delete the previous 2 lines and uncommente the following
    // update_post_meta($post_id, 'card_activity', $activity);
    // update_post_meta($post_id, 'datetime', $datetime);
    // update_post_meta($post_id, 'user', $user);        

} 

If in your metabox have you setted a nonce field check for it before save.

See Codex for:

Leave a Comment