skip to Main Content

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


  1. You can use the WP_Query to retrieve posts based on your criteria and then you can use the wp_set_post_categories() to set the category you want:

    $category_id = get_cat_ID('business');
    
    $args = array(
        's' => 'business',
        'post_type' => 'post',
        'posts_per_page' => -1,
        'category__not_in' => array($category_id),
    );
    
    $query = new WP_Query($args);
    
    if ($query->have_posts()) {
        while ($query->have_posts()) {
            $query->the_post();
            wp_set_post_categories(get_the_ID(), array($category_id));
        }
    }
    wp_reset_postdata();
    

    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:

    $args = array(
        's' => 'business*',
        // Rest of the arguments...
    );
    

    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').

    Login or Signup to reply.
  2. 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 then wp post term add to set the term on the posts.

    Here’s a Bash script I found that may work (untested):

    for post in $(wp post list --s=business --format=ids)
    do
    wp post term add $post category 'category_name'
    done
    

    Source:
    https://www.presslabs.com/code/wp-cli-guide-wp-term/

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search