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.
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.
Share Improve this question edited May 20, 2019 at 16:58 butlerblog 5,1313 gold badges28 silver badges44 bronze badges asked May 20, 2019 at 16:40 Aditya AgarwalAditya Agarwal 2764 silver badges22 bronze badges 3- 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 Commented May 20, 2019 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 Commented May 22, 2019 at 0:58
- @nmr hey, hope you would be able to help me with this piece of code. – Aditya Agarwal Commented May 23, 2019 at 13:46
1 Answer
Reset to default 0Can't give you fish, but I can try you to teach how to fish with a couple of pointers;
- hook into publish_post (good example code there) and / or post_updated
- in the function that is called that way, use wp_create_category (which will only create if the cat. name doesn't exist yet)
- 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! :)
frank