I accidentally found this question searching for something similar, and I liked your approach, so I improved your code a bit.
- I updated the action hook so it’s being triggered on save AND update.
- Added the
wp_remove_object_terms
to be able to switch back ( toggle ) custom meta box value ( in this case check-box value ).
function works fine with both, regular and custom post types, also can be used with tags, categories or custom taxonomies too.
function set_term( $post_id, $your_term ){
$post_id = get_the_ID();
$your_term = get_post_meta( $post_id, 'your_custom_meta_id', true );
// check the custom meta-box checkbox value
if ( $your_term == '1' ) {
// Create a new term if checked
wp_set_object_terms( $post_id, 'YourTerm', 'your_custom_taxonomy', true );
} else {
// Remove the created term if unchecked
wp_remove_object_terms( $post_id, 'YourTerm', 'your_custom_taxonomy' );
}
}
add_action( 'save_post', 'set_term', 10, 3 );