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"
}
}
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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' );
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0