0

I need to assign categories to about 200 posts in bulk. Each post would have a few categories. I have the post ID's along with the Category ID's for each post in a text file like this:

Post ID, Category ID, Category ID, Category ID

How could I setup a custom function inside functions.php to use wp_set_post_categories to do this task?

Thanks!

1

First, you would need to parse your text file. Using fopen and fgets you can read a file line-by-line. For every line, you separate the comma-separated list of IDs by using explode. After that, it's a case of simply calling wp_set_post_categories where the post ID is the first element of the list of IDs, and the category IDs are the other elements.

$fh = @fopen( dirname( __FILE__ ) . '/testfile.txt', 'r' );

if ( $fh ) {
    while ( ( $line = fgets( $fh ) ) !== false ) {
        // Separate by comma
        $ids = explode( ',', $line );

        // Remove leading and trailing spaces from post ID and category IDs
        array_walk( $ids, 'trim' );

        // Get and remove first element of the list of IDs, the post ID
        $postid = array_shift( $ids );

        // Set categories for the post
        wp_set_post_categories( $postid, $ids );
    }
}

Please note that wp_set_post_categories will assign the "Uncategorized" category to a post if an empty array is passed as the list of categories.

1
  • This worked like a charm from the get-go. Thank you! – kat Mar 27 '14 at 13:47

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.