Set custom post type terms by id without knowing taxonomy

admin2025-06-03  4

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.

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.

Share Improve this question asked Feb 20, 2019 at 9:43 mistertaylormistertaylor 6411 gold badge6 silver badges20 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 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 );
}
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1748886219a314539.html

最新回复(0)