Import CSV Data To WordPress Using Custom Plugin


About The Author
Cabe Nolan is the founder of WP Cover where he shares his insight into WordPress, development, & entrepreneurship. Outside of WPCover, Cabe continues to run a successful WordPress development firm, Bold City Design as well as a few high profile websites, Arrivala, Two Way Resume, Dock Skipper, and a successful outdoors brand, DolfinPack.







Import CSV Data To WordPress Using Custom Plugin

When you start working with large WordPress sites you frequently need to update mass amounts of data.  Or in some cases add mass amounts of data.  The easiest way to do this is normally through spreadsheets.  There are a handful of plugins out there that handle common CSV importing and exporting but I’ve found many of them to be confusing, bloated and/or require different add-ons to be purchased depending on the task you need to complete.

This morning I had a task of updating every WordPress term within the custom taxonomy of ‘location’ with latitude and longitude data.  I already had the term ID, latitude and longitude stored in a neat spreadsheet but my searches for a pre-existing plugin that could handle the updating was getting me nowhere.  I’m not saying there’s not a plugin out there that will do this, but I didn’t feel like spending two hours researching, installing, re-formatting spreadsheets, receiving errors, etc. when I knew I could write my own custom plugin much quicker.  And as a bonus, it would give me a nice article to share with you.

Here It Goes:

As is the case with most plugins I create, I start with my handy framework for building a plugin to do ‘Random’ things.  From there, I modified the plugin to handle my CSV import, process the file and loop through the rows of data (beginning with row 2).  As you will see from the code, I had three rows of data in my spreadsheet, the first being the term ID, the second being the latitude coordinate and the third being the longitude coordinate.  Here is the file I uploaded in if you want to check it out.  We’re leveraging Advanced Custom Fields update_field function to update the term data within the loop.  Therefore, you’ll need to ensure that plugin is installed and activated as well.

Here is the full plugin code:

<?php
/**
* Plugin Name: Custom CSV Importer - WP Cover
* Plugin URI: https://www.wpcover.com
* Description: Custom plugin by Cabe to do random repetitive tasks when and where I need it to be done. The "Heavy Lifter"
* Version: 1.0
* Author: Cabe Nolan
* Author URI: https://www.boldcitydesign.com
* License: GPL12
*/
 
/*---------------------------------------------------
add settings page to menu
----------------------------------------------------*/
function add_rstuff_import_page() {
add_submenu_page( 'tools.php', 'Import CSV Custom', 'Import CSV Custom', 'manage_options', 'import-rstuff', 'import_rstuff' );
}
add_action( 'admin_menu', 'add_rstuff_import_page' );
 
function import_rstuff() {
?>
 
<div class="wrap import-csv">
    <h2>Import CSV Custom</h2>
    <p>Click Process button to do whatever is below in your run process.</p>
<?php
    if ( isset( $_POST['_wpnonce-is-iu-import-users-users-page_import_cn'] ) ) {
    check_admin_referer( 'is-iu-import-users-users-page_import_cn', '_wpnonce-is-iu-import-users-users-page_import_cn' );
        
        ini_set("auto_detect_line_endings", true);
		//start processing the CSV
		if (!empty($_FILES['users_csv_cn']['name'])) {
			// Setup settings variables
			$filename = $_FILES['users_csv_cn']['tmp_name'];
			$file_handle = fopen($filename,"r");
			$i=0;
			$imported = 0;
			$failedusers = array();
			$successusers = array();
			while (!feof($file_handle) ) {
				$block = 0;
				$check = 0;
				$line_of_text = fgetcsv($file_handle, 1024);
				// Let's make sure fields have data and it is not line 1
				if(!empty($line_of_text[0])) {
					$i++;
					if($i > 1 && $i < 302) {
					$imported++;	
						//start new import
						
						$locationID = sanitize_text_field($line_of_text[0]);
						$locationLat = sanitize_text_field($line_of_text[1]);
						$locationLng = sanitize_text_field($line_of_text[2]);
						$refpost = 'location_' . $locationID;
						update_field( 'latitude', $locationLat, $refpost );
						update_field( 'longitude', $locationLng, $refpost );
						echo 'Updated Term ID ' . $locationID . ' - ' . $locationLat . ', ' . $locationLng . '<br />'; 
						
						
        
        
					}
				}
			}
		fclose($file_handle);
		echo 'Updated ' . $imported . ' terms';
		} else {
			echo 'Fail';
		}
    }
    ?>
 
    <form method="post" action="" enctype="multipart/form-data">
	    <input type="file" id="users_csv" name="users_csv_cn" value="" class="all-options" />
        <?php wp_nonce_field( 'is-iu-import-users-users-page_import_cn', '_wpnonce-is-iu-import-users-users-page_import_cn' ); ?>
        <p class="submit">
            <input type="submit" class="button-primary" value="Process Posts" />
        </p>
    </form>
<?php } ?>

Hope this helps somebody else with quick CSV imports. The base of this code could be tweaked in many ways to perform an infinite number of tasks on a WordPress database.


Share Your Thoughts

Leave a Reply

Your email address will not be published. Required fields are marked *


Related Stuff You Might Like







20% Off WP Engine

WordPress News, Tips, & Code Snippets

Join the WP Cover mailing list and get wordpress news, tips, code snippets, security warnings, and more delivered right to your inbox.  We won't flood your inbox, newsletters typically go out every 1-2 weeks unless it involves an important security release.

You have Successfully Subscribed!