Skip to content

Instantly share code, notes, and snippets.

@steve10287
Created January 17, 2022 10:10
Show Gist options
  • Save steve10287/89ee5506432400f86a17b8d12181fbc5 to your computer and use it in GitHub Desktop.
Save steve10287/89ee5506432400f86a17b8d12181fbc5 to your computer and use it in GitHub Desktop.
Wordpress Insert Post Terms
/**
* 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);
}
@steve10287
Copy link
Author

Remember to only interact with Taxonomies after the taxonomy has been registered, in most cases in the init action.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment