I am fairly new to PHP. I wanted a code snippet to create post category from the post title. If the post title does exists as a category, then assign the post to that category. If the category doesn't exist, create a category from the post title.

The code snippet should also update the category in case the title changes after post update.

I very well know that my need for this code would be needed by others also. I also know that too many categories for posts are bad. But it is for a better design.

Please help me to set a category/update the category as the exact title of post.

  • 1
    Categories are usually used to group posts. For what purpose, create categories that can only have one post? Maybe there is another way to achieve what you need? – nmr May 20 at 17:39
  • @nmr Hi, Sorry For Late reply. On my site multiple users can register and write posts. It is similar to stack overflow. On stack we can have multiple answers to the same question. On my site we can have multiple posts on same title. I plan to make the title as category, so that readers can go to that category and view all posts that are similar. I know it would harm SEO, but I still want to do it. – Aditya Agarwal May 22 at 0:58
  • @nmr hey, hope you would be able to help me with this piece of code. – Aditya Agarwal May 23 at 13:46

Can't give you fish, but I can try you to teach how to fish with a couple of pointers;

  1. hook into publish_post (good example code there) and / or post_updated
  2. in the function that is called that way, use wp_create_category (which will only create if the cat. name doesn't exist yet)
  3. and with the cat ID you get that you then call wp_set_post_categories (make sure to set the 3rd param to true)

happy coding! :)


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.