1

For a custom post type with multiple taxonomies, is it possible to set the post terms without explicitly knowing which taxonomy the term falls under?

I have an array of term ids which may contain a mix of terms from any one of three taxonomies. The only function I've found to add terms to a cpt is wp_set_post_terms which requires the taxonomy slug.

1 Answer 1

3

It's a bit confusing, the documentation for wp_set_post_terms() claims that the $taxonomy argument is "Optional", but in looking at the source it appears that all this means is that its default value is post_tag if you omit the argument. If you attempt to pass null or an empty string, it won't work.

So I think the solution then would be to first get the taxonomies of the given IDs, and then set the terms for each taxonomy separately.

$post_id  = 123; // For example.
$term_ids = [ 1, 2, 3 ]; // For example.

$terms = [];

foreach ( $term_ids as $term_id ) {
    $term = get_term( $term_id );

    $terms[$term->taxonomy][] = $term_id;
}

foreach ( $terms as $taxonomy => $term_ids ) {
    wp_set_post_terms( $post_id, $term_ids, $taxonomy );
}
2
  • Thanks, that's a bit more succinct than my solution. Commented Feb 20, 2019 at 10:23
  • I would set the append parameter of wp_set_post_terms to true to avoid overwriting terms with same taxonomies
    – RafaSashi
    Commented Jun 27, 2023 at 4:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.