Skip to content

Instantly share code, notes, and snippets.

@petenelson
Last active March 28, 2024 19:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save petenelson/bac421e2dbb9373682364b2ad87f2d39 to your computer and use it in GitHub Desktop.
Save petenelson/bac421e2dbb9373682364b2ad87f2d39 to your computer and use it in GitHub Desktop.
WordPress: Get term IDs, creates terms if they don't exist
/**
* Gets the term IDs for the term names. Creates the terms if they do not exist.
* TODO update the project_name_term_id_created filter when you copy/paste this function.
*
* @param string $term_names The term name (or names separated with pipes).
* @param string $taxonomy The taxonomy.
* @param string $by Get term by 'name' or 'slug'?
* @param bool $create Create the term if it doesn't exist?
* @return array
*/
function get_term_ids( $term_names, $taxonomy, $by = 'name', $create = true ) {
$term_ids = [];
if ( ! taxonomy_exists( $taxonomy ) ) {
return $term_ids;
}
foreach ( explode( '|', $term_names ) as $term_name ) {
$term_name = trim( $term_name );
if ( empty( $term_name ) ) {
continue;
}
$term_data = false;
// Only allow lookups by name or slug.
if ( 'name' !== $by && 'slug' !== $by ) {
$by = 'name';
}
$existing_term = get_term_by( $by, $term_name, $taxonomy );
if ( $existing_term instanceof \WP_Term ) {
$term_data = [ 'term_id' => $existing_term->term_id ];
}
if ( ! is_array( $term_data ) ) {
if ( $create ) {
$term_data = wp_insert_term( $term_name, $taxonomy );
if ( is_array( $term_data ) ) {
// Work around an existing bug in https://github.com/Automattic/vip-go-mu-plugins/issues/1832.
$cache_key = $term_name . '|' . $taxonomy;
$cache_group = 'term_exists';
wp_cache_delete( $cache_key, $cache_group );
do_action( 'project_name_term_id_created', $term_data['term_id'] );
}
}
}
if ( is_array( $term_data ) ) {
$term_ids[] = $term_data['term_id'];
}
}
return array_map( 'absint', $term_ids );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment