How to assign tag to custom post type in wordpress?

Question

I’m pretty stuck on this wordpress challenge where I need to programmatically assign a taxonomy to a custom post type. How can I successfully assigned programmatically a tag to a custom post type? Im not too sure what I’m doing wrong here.
This is my tag:

wp> $tagOne = get_term_by('slug', 'dogs-cats','pets_tag');
=> object(WP_Term)#3015 (10) {
  ["term_id"]=>
  int(20)
  ["name"]=>
  string(20) "Dogs & Cats"
  ["slug"]=>
  string(14) "dogs-cats"
  ["term_group"]=>
  int(0)
  ["term_taxonomy_id"]=>
  int(20)
  ["taxonomy"]=>
  string(12) "pets_tag"
  ["description"]=>
  string(0) ""
  ["parent"]=>
  int(0)
  ["count"]=>
  int(0)
  ["filter"]=>
  string(3) "raw"
}

This is my array of tag term ids:

wp> $tagsIdArray = array($tagOne->term_id)
=> array(1) {
  [0]=>
  int(20)
}

This is my wordpress command to assign pet post 3356 to the above tag:

wp> wp_set_object_terms(3356, $tagsIdArray, 'pets_tag', false);
=> array(1) {
  [0]=>
  string(2) "20"
}

When I go to query the tags for the above post, I see that a new tag has been created and not an assignment of an existing tag to the above post:

wp> get_the_tags(3356)
=> array(1) {
  [0]=>
  object(WP_Term)#3011 (10) {
    ["term_id"]=>
    int(25)
    ["name"]=>
    string(14) "dogs-cats"
    ["slug"]=>
    string(14) "dogs-cats"
    ["term_group"]=>
    int(0)
    ["term_taxonomy_id"]=>
    int(25)
    ["taxonomy"]=>
    string(8) "post_tag"
    ["description"]=>
    string(0) ""
    ["parent"]=>
    int(0)
    ["count"]=>
    int(0)
    ["filter"]=>
    string(3) "raw"
  }
}
0
robskrob 2 months 0 Answers 13 views 0

Leave an answer