I want to add all posts with keyword “Dog Training” in the post title to a specific category.
Reason: If you enter something into WordPress search it’s not an exact match. Previous WordPress search was much more accurate but they gimped it now. Note the space between the words.
You have to check the existing terms first with
wp_get_object_terms()
and if the term you need is missing, add it withwp_set_object_terms()
.It is faster to update the terms just once than to do this for every term.
The following example is running on
save_post
. I put everything into a class (and into a plugin) to make the code more readable. You could use just one function tough.To keep things flexible I implemented three matching algorithms: exact, case-insensitive and regular expression (regex).
The terms must exist already. I choose this requirement to prevent accidental mismatches.
Here I have written a post with the title a test with wORdpReSs and 22kg Dog Training and then I hit Save Draft once:
To update existing posts run something like the following once: