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

I have a custom content type called cards.

I have 3 custom meta fields called:

Read More

my_cards_activity (select field type; options 0 and 1)

my_cards_user (select type; many options)

my_cards_datetime (text field type; yyyy-mm-dd hh:mm format)

When I press SAVE button I want to get the value of the my_cards_activity field (value can be 0 or 1) and if the value is 0 then change my_cards_datetime and my_cards_user to empty value and only after the change save it all. If it is 1 then do nothing.

How to do such before save thing? How should my code in functions.php look like?

Related posts

1 comment

  1. 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:

Comments are closed.