Last active
January 19, 2023 09:34
-
-
Save aliboy08/bb50355c83e06fa1e887575d92df1b8f to your computer and use it in GitHub Desktop.
Set term to post id, create term if it does not exist
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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