I have a custom post type, ‘albums’. In it is a taxonomy, ‘album_artist’. I am trying to programatically add artists to that taxonomy using wp_set_object_terms in a function that’s hooked into save_post.
function get_album_data($post_id) {
// CODE REMOVED FOR BREVITY: IMPORT DATA FROM EXTERNAL SOURCE, PARSE VARS
wp_set_object_terms( $post_id, $album_artist_name, 'album_artist', true );
update_post_meta ($post_id, 'Release Date', $release);
}
add_action( 'save_post', 'get_album_data', 1001 );
I’m using “true” for those cases where, on a compilation album, there is more than one artist (think “21 Original Hits 21 Original Stars”).
Going through the wp_terms, wp_term_relationships and wp_term_taxonomy tables in the DB, here’s what I’m seeing:
- In wp_terms, the terms are being created properly, with correct slugs (ie “The Police” get a slug of the-police, and term_id 482)
- In wp_term_taxonomy, the term is showing up under the right taxonomy (ie term_taxonomy_id 506 has term_id 482 with a taxonomy of album_artist)
- In wp_term_relationships, term_taxonomy_id 506 shows with object_id 2448
Looks good, right? Sadly, no. Because object_id 2448 refers to POST 2448, which is actually a REVISION of 2447. And when I check the wp_postmeta table, the ‘release_date’ meta has been updated on 2447, not 2448.
So WP seems to be creating a relationship to the wrong post. That’s why, I assume, the artist isn’t showing up on my album page the way it would if I went into the “Artist” metabox and clicked the checkbox that says “The Police”.
And yet, it seems to treat the $post_id variable differently in a update_post_meta versus a wp_set_object_terms. Because the two statements literally are adjacent to each other in the function, yet the $post_id variable means different things to different functions.
How do I force WP to make the relationship between the terms and the PARENT, instead of the revision?
Use
wp_is_post_revision()
function which will give youfalse
if post is not a revision (in which case just work as usual with that) or actual post ID to use instead of revision’s.