Mass/Bulk assign categories to posts

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.

Leave a Comment