2
votes

I have a custom function that works with my custom post type. While porocessing save_post action:

add_action( 'save_post', 'my_custom_function' );

I would like to set post status as draft (in case of a problem with getting custom data from outside api). In my my_custom_function function I have this little block:

if ($error == true) {
    $override_post = array();
    $override_post['ID'] = $post_id;
    $override_post['post_status'] = 'draft';
    wp_update_post( $override_post );
}

but it seems, that after save_post is being processed, then post_status is being set again.

Anybody have an idea, where should I hook into, so while saving post data I can modify its post_status, post_date and some other post data informations so they are not being overriten?

2

2 Answers

4
votes

You should hook it to wp_insert_post_data. Then you could use a function like this to set your post status to draft:

add_filter( 'wp_insert_post_data', 'set_post_to_draft', 99, 2 );

function set_post_to_draft( $data, $postarr ) {

  if ( your_condition ) {
    $data['post_status'] = 'draft';
  }

  return $data;
}
0
votes

I had to make a post type with only one post_status option, and it seem to fit your needs too, as it is works exactly with the save_post hook.

add_action( 'save_post', 'my_function' );
function my_function( $post_id ){
    if ( ! wp_is_post_revision( $post_id ) ){
        // avoid endless circle
        remove_action('save_post', 'my_function');

        // update the data before saving
        wp_update_post( wp_slash([
            'ID' => $_POST['ID'],
            'post_status' => 'draft'
        ]));

        // restore the saving hook
        add_action('save_post', 'my_function');
    }
}

The original solution found here: https://wp-kama.ru/function/wp_update_post