php - Copy taxonomy terms from one post to another programmatically

admin2025-06-02  7

Let's say i have a post with post id "1" and post with post id "2".

And i have a custom taxonomy named "my_taxonomy".

The post with post id "1" has: "term1","term2","term3" selected for the "my_taxonomy" terms.

And the post with post id "2" has: "term3","term4","term5" selected for the "my_taxonomy" terms.

I want to programmatically copy the terms from first post to second so the post with post id "2" will have: "term1","term2","term3" selected for the "my_taxonomy" terms now.

How can i do that the most "short coded way" ?

A note: both posts are a custom post type posts.

I tried:

wp_set_object_terms( '2', wp_get_object_terms( '1', 'my_taxonomy' ), 'my_taxonomy');

Doesn't seem to work.

Let's say i have a post with post id "1" and post with post id "2".

And i have a custom taxonomy named "my_taxonomy".

The post with post id "1" has: "term1","term2","term3" selected for the "my_taxonomy" terms.

And the post with post id "2" has: "term3","term4","term5" selected for the "my_taxonomy" terms.

I want to programmatically copy the terms from first post to second so the post with post id "2" will have: "term1","term2","term3" selected for the "my_taxonomy" terms now.

How can i do that the most "short coded way" ?

A note: both posts are a custom post type posts.

I tried:

wp_set_object_terms( '2', wp_get_object_terms( '1', 'my_taxonomy' ), 'my_taxonomy');

Doesn't seem to work.

Share Improve this question edited Jul 26, 2017 at 9:17 mondi asked Jul 26, 2017 at 8:43 mondimondi 2551 silver badge6 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 2

This will work:

wp_set_object_terms( 
    '2', 
    wp_get_object_terms( 
        '1', 
        'my_taxonomy', 
        array("fields"=>"ids") 
    ), 
   'my_taxonomy'
);

Explanation:

I added this: ,array("fields"=>"ids") to the attempt i wrote in the question to make the wp_get_object_terms return array of ids alone (what the wp_set_object_terms want to get.

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1748829094a314066.html

最新回复(0)