Since i’ve thousands of articles the bulk edit is impossible. It will require too much time and with 999 articles a time WordPress will already crash.
So i thought about using a simple db query but i’m not sure how to build it.
How can i set a specific category for every post containing a specific word?
For example i want to put into the "business" category every article containing the "business" word.
What kind of query should i use?
I tried something i found here but without any success. The answer are always not clear or suggesting to use the bulk edit function that is something i can’t use.
2
Answers
You can use the
WP_Query
to retrieve posts based on your criteria and then you can use thewp_set_post_categories()
to set the category you want:In the above query, the ‘s’ parameter is used to specify the search term . It searches for the exact word "business" in the post title, post content, and post excerpt.
It won’t match variations of the word or partial matches. If you also want the word "businesses" or "businessman," then you can use the ‘s’ parameter with wildcards:
Make sure you only run the above query once, so don’t leave it inside a
functions.php
file otherwise it will be executed every time you load a page.Depending on your server’s specs, it might timeout if you have many thousands of matched posts. Just run the query again and it will complete, since it will skip the posts from previous runs (
'category__not_in'
).Using WP CLI commands is the most performant way of doing this: it’s high performant, and uses WordPress functions (mentioned by GeorgeP).
Use
wp post list
to get the list of posts, and thenwp post term add
to set the term on the posts.Here’s a Bash script I found that may work (untested):
Source:
https://www.presslabs.com/code/wp-cli-guide-wp-term/