0

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"
  }
}

1 Answer 1

2

You actually correctly assigned the tag to the post, but the taxonomy is pets_tag, so you shouldn't use get_the_tags() which is for the default post_tag taxonomy.

Instead, you should use get_the_terms() to get the pets_tag terms assigned to the post:

$terms = get_the_terms( 3356, 'pets_tag' );

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.