How can I add programmatically custom taxonomy terms to a custom type post when saving posts?

So, to answer my own question:

I haven’t found any solution inside wp_insert_post_data. I suspect that the problem is connected to the fact that when wp_insert_post_data is executed the post in question is not yet in the database. And albeit I didn’t manage to find it in taxonomy.php, it is logical to assume that the wp_set_post_terms function have some checking mechanism to avoid inserting term relationships with arbitrary/non-existent post ID’s.

Anyhow, in wp_insert_post_data I defined a global variable to store the tax term which needs to be added (instead of trying to add it locally). Then I hooked into save_post, which is executed after the post have been saved, and retrieved/inserted the term from there.

Seem to work just fine.

The relevant code part in wp_insert_post_data:

...

// Fill in Author tag with Amazon data if missing
if ( ! has_term( $book_data[1], 'author', $postarr['ID'] ) ) {
    global $add_this_tax_term_to_book;
    $add_this_tax_term_to_book[] = $book_data[1];
    $add_this_tax_term_to_book[] = 'author';
}

...

And the code for save_post:

add_action('save_post', 'add_my_tax_term');
function add_my_tax_term( $post_id ) {
    global $add_this_tax_term_to_book;

    if ( !(empty( $add_this_tax_term_to_book )) ) {
        wp_set_object_terms( $post_id, $add_this_tax_term_to_book[0], $add_this_tax_term_to_book[1] );
}

Leave a Comment