Skip to content

Instantly share code, notes, and snippets.

@aliboy08
Last active January 19, 2023 09:34
Show Gist options
  • Save aliboy08/bb50355c83e06fa1e887575d92df1b8f to your computer and use it in GitHub Desktop.
Save aliboy08/bb50355c83e06fa1e887575d92df1b8f to your computer and use it in GitHub Desktop.
Set term to post id, create term if it does not exist
// Set post term to post id, create term if it does not exist
function ff_set_post_term_with_fallback($post_id, $value, $taxonomy, $create_new = true ){
if( $value == '' ) return;
// Search term
$term = term_exists( $value, $taxonomy);
if( $term ) {
// Term exists
wp_set_post_terms( $post_id, $term['term_id'], $taxonomy, true );
} else {
// Term does not exist, create new
if( $create_new ) {
// Create new term
$new_term = wp_insert_term($value, $taxonomy);
if( $new_term ) {
wp_set_post_terms( $post_id, $new_term, $taxonomy, true );
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment