How to Import Categories with Descriptions from a CSV File?

How could I import a list of new categories and category descriptions from a file of Comma Separated Values?

Related posts

Leave a Reply

1 comment

  1. Very simple plugin to achieve this.

    Runs only on activation, so, if there are 5 CSV files, the plugin must be activated/deactivated five times.

    File:

    /wp-content/plugins/create-cats-from-csv/create-cats-from-csv.php

    <?php
    /*
        Plugin Name: Insert CSV Categories
        Version: 1.0
        Description: Reads a CSV file on plugin activation and insert the Categories/Description/Parent into WordPress as defined in the CSV
        Plugin URI: http://wordpress.stackexchange.com/q/57865/12615
        Author: brasofilo 
        Author URI: http://rodbuaiz.com
    */
    register_activation_hook(__FILE__, 'wpse_57865_activation_run');
    
    function wpse_57865_activation_run()
    {
        // THE PREG_SPLIT IS NOT ADEQUATE FOR COMPLEX STRINGS
        // Code snippet: http://stackoverflow.com/q/7502370/1287812
        $file = file_get_contents( plugin_dir_path( __FILE__ )  . 'categories.csv' );
        $data = array_map( "str_getcsv", preg_split( '/r*n+|r+/', $file ) );
    
        if( count($data) < 1)
            return;
    
        // http://codex.wordpress.org/Function_Reference/wp_insert_category
        foreach( $data as $cat )
        {
            $cat_defaults = array(
              'cat_name' => $cat[0],
              'category_description' => $cat[1] 
            );
    
            wp_insert_category($cat_defaults);
        }
    
    }
    

    File:

    /wp-content/plugins/create-cats-from-csv/categories.csv

    Category Title, Category Description
    First Category, Lorem ipsum dolor sit amet
    Second Category, Consectetur adipisicing elit
    Third Category, Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua