$conf, $runtime; function_exists('chdir') AND chdir(APP_PATH); $r = 'mysql' == $conf['cache']['type'] ? website_set('runtime', $runtime) : cache_set('runtime', $runtime); } function runtime_truncate() { global $conf; 'mysql' == $conf['cache']['type'] ? website_set('runtime', '') : cache_delete('runtime'); } register_shutdown_function('runtime_save'); ?>Set custom post type terms by id without knowing taxonomy|Programmer puzzle solving
最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

Set custom post type terms by id without knowing taxonomy

matteradmin10PV0评论

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 );
}
Post a comment

comment list (0)

  1. No comments so far