wp_set_object_terms Not Updating unless I click update twice

Question

I am using code from this answer to create a new child taxonomy term, however for some reason the change only takes effect if I click update post twice. Clicking Update Post once doesn’t save the change.

Here is the code from the answer of the linked question.

add_action('save_post_cpt', 'run_on_update');

function run_on_update($post_id) {
// $_POST['input_name']; is an array
//get the array and sanitize it
$input_terms = array_map( 'sanitize_text_field', $_POST['input_name'] );
//Set the array of terms for later use on wp_set_object_terms
$terms = array();
foreach( $input_terms as $term ) {
    
    $existent_term = term_exists( $term, 'the_tax' );

    if( $existent_term && isset($existent_term['term_id']) ) {

        $term_id = $existent_term['term_id'];

    } else {

        //intert the term if it doesn't exsit
        $term = wp_insert_term(
            $term, // the term 
            'the_tax', // the taxonomy
            array(
                    'parent' => 3, // ID of parent tax term
                )
        );
        if( !is_wp_error($term ) && isset($term['term_id']) ) {
             $term_id = $term['term_id'];
        } 

   }

   //Fill the array of terms for later use on wp_set_object_terms
   $terms[] = (int) $term_id;

}

wp_set_object_terms( $post_id, $terms, 'the_tax' );
}

I did see this answer about wp cache interfering, however according to the last answer on that post that issue was fixed years ago.

Any help is greatly appreciated!

0
Harvey 1 month 0 Answers 7 views 0

Leave an answer