The first thing to do is to create an array of categories id. Once done, you simply have to use the wp_set_object() function, which take 3 parameters: The post id, an array of categories to add to the post, and the taxonomy type (category in this example).
$category_ids = array(4, 5, 6);
wp_set_object_terms( $post_id, $category_ids, 'category');
Adding tags to a post is extremely easy as well. The only difference with the code to add categories is the taxonomy "post_tag" instead of "category".
$tag_ids = array(7, 8, 9);
wp_set_object_terms( $post_id, $tag_ids, 'post_tag');
Thanks to WPProgrammer for this very cool snippet.
11 Responses
Thank you VERY much for these snippets!
Can I please ask for just a bit of clarification on two things that I cannot figure out?
1. When you say place the snippet in the functions.php, will you ALWAYS mean the theme’s functions.php unless specifically stating otherwise? Or do you mean the PRIMARY function.php unless specifically stating otherwise?
and 2. When you say “programatically”, what is your definition of the word? I’m not asking for ANY other reason, but to fully comprehend your lingo, so I can get my head fully wrapped around your tips and tricks.
Thank you VERY much!
@MacDaddy: Yes, the theme functions.php. You shouldn’t alter any WP core files.
By “programatically”, I mean use programming instructions, not manual actions.
Hope it is more clear now
@Jean-Baptiste Jung: It is MUCH clearer now, and I thank you for taking the time to explain it for me.
Wow, so simple
. It seems that wordpress has a build in function for everything.
Please explain why you would need this. From what I can tell this is specific to a single post rather than a group of posts?
On topic, but off topic…
How would you go about taking a group of posts (that all share a specific tag) and add them to a specific category?
Maybe better asked, how can I turn a tag into a category?
nice tips thx,
but how adding new tag who don’t already exist ?
hi all ,
I have created a dashboard using 10000 as max number of rows , but i can generate the SWF file,can someone help ?
Thank in Advance
Regards
I like your posts, but would be cool to get some answers to some of the questions i have asked. OR are these comment areas just to allow people to post ‘first’ or ‘love the post’ which offer nothing to the conversation?
why delete comments?
@Timmy: Comments are deleted only when they are spammy, contain a wrong email (like yours, excepted if you own home.com, which I doubt) or contains links.
Regarding questions, I’d love to answer them but there’s 300 posts on this blog. Answering the 50 questions I get everyday will take definitely too much time.
Trackbacks: