WordPress is the most popular CMS and with WordPress building a website is very quick and easy. Today I am going to explain about to import terms like (categories, tags, or terms of custom taxonomy) from CSV into WordPress.
Here, I am going to explain code step by step:
First of all, create one file into root folder where you have stored WordPress or you can create into your theme folder. If you create file into theme, you need to change $base_dir value variable.
1 2 3 4 |
Next,we will calls csv_to_array function which get data from csv file and convert the data to array. After receiving it as array,calling a function flatter_array converted multidimensional array to single dimension array.
Now, foreach loop to insert one by one data as term into WordPress.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 | global $wpdb; $array_data = csv_to_array('csv_key.csv'); foreach($array_data as $data) { $data = trim($data); if($data != '') { //Replace <taxonomy> with your desired taxonomy. $term_exists = term_exists($data, ‘<taxonomy>’); if ($term_exists !== 0 && $term_exists !== null) { echo $term_exists->name." exists!<br/>"; }else { $term = wp_insert_term($data, '<taxonomy>'); echo $term->name." inserted Successfully<br/>"; } } } // function to convert csv data into array function csv_to_array($filename='', $delimiter=',') { if(!file_exists($filename) || !is_readable($filename)) return FALSE; $data = array(); if (($handle = fopen($filename, 'r')) !== FALSE) { while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE) { array_push($data,$row); } fclose($handle); } return flatter_array($data); } // To convert multi dimensional array to single dimension function flatter_array($array) { if (!is_array($array)) { return FALSE; } $result = array(); foreach ($array as $key => $value) { if (is_array($value)) { $result = array_merge($result, array_flatten($value)); } else { $result[$key] = $value; } } return $result; } |
That’s it place above code into the file, your CSV file and replace with your desired taxonomy in wp_insert_term function.
Also Read:
Disable updates for specific plugin in WordPress
To get Last auto increment id in WordPress
To import user from CSV in WordPress
Hope this helps someone else out.As always, thanks for reading. Don’t Forget to Follow us on Twitter or Subscribe us to Get the Latest Updates.