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!
pre_post_update
action instead ofsave_post_
- looking at the way it's handled in thewp_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 thesave_post_
action, and you doing it after the fact isn't letting WP properly make those connections.pre_post_update
it didn't even save the change.