Created
January 17, 2022 10:10
-
-
Save steve10287/89ee5506432400f86a17b8d12181fbc5 to your computer and use it in GitHub Desktop.
Wordpress Insert Post Terms
This file contains hidden or 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
/** | |
* Insert post terms | |
* | |
* @param array|string $terms | |
* @param integer $post_id | |
* @return void | |
*/ | |
function _insertPostTerms($terms, $post_id, $taxonomy) | |
{ | |
$term_ids = []; | |
foreach ((array) $terms as $term) | |
{ | |
$term_id = term_exists($term, $taxonomy); | |
if(!$term_id) | |
{ | |
$term_id = wp_insert_term($term, $taxonomy); | |
} | |
$term_ids[] = (int) $term_id['term_id']; | |
} | |
wp_set_post_terms($post_id, $term_ids, $taxonomy); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Remember to only interact with Taxonomies after the taxonomy has been registered, in most cases in the init action.