0

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. (The solution there was to insert delete_option("{$taxonomy}_children"); right after the term is added, but even that doesn't work.

Any help is greatly appreciated!

2
  • You may want to look at the pre_post_update action instead of save_post_ - looking at the way it's handled in the wp_insert_post() function, terms are updated before the actual call to the database. I haven't dug in but I'm wondering if WordPress does some house keeping for terms on the post before it fires the save_post_ action, and you doing it after the fact isn't letting WP properly make those connections.
    – phatskat
    Commented Dec 16, 2020 at 15:26
  • @phatskat Thanks for your reply! Unfortunately when I used the hook pre_post_update it didn't even save the change.
    – harvey
    Commented Dec 16, 2020 at 18:37

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.