Wordpress csv Importer Custom Fields Plugin
X

Congrats, You are Subscribed to Receive Updates.

WordPress csv Importer Custom Fields Plugin


WordPress csv Importer Custom Fields Plugin.The very first thing you have to do while creating a plugin or a theme or a template is to define at the top of the file.

csv-wp

So, here for a plugin we have to define the following attributes.

/*
Plugin Name: Kv_CSV Upload
Description: It is to upload data from CSV to DB
Version: 1
Author: Karthikeyan P
Author URI:www.facebook.com/karthiglister
*/

The above details describe this is a plugin file. Once we defined plugin name and other attributes then we need to create an admin menu. Name this file as init.php

add_action('admin_menu','csv_modifymenu');
add_action('admin_init', 'kv_create_tables');
function csv_modifymenu() {
	add_menu_page('CSV  Upload', //page title
	'CSV Upload', //menu title
	'manage_options', //capabilities
	'csv_plugin_home', //menu slug
	'csv_plugin_home' //function
	);

The above function creates admin menu and then if you need to create a sub menu then you can use “add_submenu_page” function.

add_submenu_page('csv_plugin_home', //parent slug
	'Upload Csv', //page title
	'Add New', //menu title
	'manage_options', //capability
	'upload_new', //menu slug
	'upload_new'); //function
}

Now admin menu and sub menu has been created. Then we have to create a function for uploading new CSV and a home page to show what has been uploaded.

First, define ROOTDIR of the plugin using the built-in function plugin_dir_path(__FILE__)

define(‘ROOTDIR’, plugin_dir_path(__FILE__));

Now include the other two functions. I have created a separate file for each function and included here.

require_once(ROOTDIR . ‘csv_plugin_home.php’);

require_once(ROOTDIR . ‘upload_new.php’);

Then we need to create a table for our CSV to be uploaded here. I have created a example table as inserting some items with price and descriptions.

if(!function_exists('kv_create_tables')) 
{
function ww_create_tables () 
{
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
	
	//global $wpdb;
	$table_name = $wpdb->prefix.'price_details';	

$sql_table = "CREATE TABLE IF NOT EXISTS $table_name (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `date` varchar(50) NOT NULL,
  `stock` varchar(50) NOT NULL,
  `item_number` varchar(15) NOT NULL,
  `description` varchar(255) NOT NULL,
  `price` varchar(15) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;";
dbDelta($sql_table);
}
}

Well, now the init file has been finished.

Let’s do the other two functions such as uploading new CSV and a Home Page of our plugin.

upload_new.php

<?php
function upload_new()
{
global $wpdb;
if(isset($_POST['upfile']))
{
if ($_FILES['uploaded'][size] > 0) { 

    //get the csv file 
	$fext=$file = $_FILES['uploaded']['name']; 
    $file = $_FILES['uploaded']['tmp_name']; 
	$ext = pathinfo($fext, PATHINFO_EXTENSION);
	if($ext=='csv')
	{
    $handle = fopen($file,"r"); 
     $table_name = $wpdb->prefix.'price_details';
	$trunc= $wpdb->query("TRUNCATE TABLE `$table_name`");
	$wpdb->get_results( "SELECT * FROM `$table_name`");
    $nrows=$wpdb->num_rows;
	if($trunc || $nrows==0 )
	{
	 fgetcsv($handle);
	 //loop through the csv file and insert into database 
    do { 
        if ($data[0]) { 
            $wpdb->insert($table_name, array('date'=>$data[0],'stock'=>$data[1],'item_number'=>$data[2],'description'=>$data[3],'price'=>$data[4]),array('%s','%d','%s','%s','%s')); 
			} 
    } while ($data = fgetcsv($handle,1000,",","'")); 
  }
  else
  {
  echo "Old Data Can't be Deleted";
  }
?>
<div> <h1>Data Uploaded Successfully</h1></div>
<?php
}
else
{
?>
<h1>You Must Upload Only CSV with .CSV Extension</h1>
<?php
}
}
else
{
?><h1>Oops! Something Went Wrong!</h1>Try again if problem persists contact Developer <?php
}
}
?>
<div class="wrap">
<form method="post" enctype="multipart/form-data" action="<?php echo $_SERVER['REQUEST_URI']; ?>">
<table class="form-table">
<h3>Import CSV Data</h3>
	File:<input name="uploaded" type="file" id="csvfile"/>
	<input type="submit" name="upfile" value="Upload File">
</form>
</table>
</div>
<?php
}
add_action('upload_new', 'upload_new');
?> 

The above code parses and inserts the data from CSV to Table, but i made CSV upload plugin as to truncate table and upload the data. You can change it to append or just write back to me if you want it to append data.

csv_plugin_home.php

<?php
function price_plugin_home()
{
?>
<html>
<div id="wrap">
<br>
<br>
<form action="" name="PTcontent" method="post">
From <input type="text" placeholder="Starting Row Number" name="rfrom"> To <input type="text" placeholder="Ending Row Number" name="rto">
<input type="submit" name="rlsub">
</form>
<p> By default it shows First 10 Rows </p>
<?php
if(isset($_POST['rlsub']))
{
$rlfrom=$_POST['rfrom'];
$rlto=$_POST['rto'];
}
else
{
$rlfrom=0;
$rlto=10;
}
global $wpdb;
$tname=$wpdb->prefix.'price_details';
$result = $wpdb->get_results( "SELECT * FROM $tname limit $rlfrom,$rlto");
?>
<p>Rows from <?php echo $rlfrom;?> to <?php echo $rlto;?></p>
<table name="price_content">
<th>Item Number</th><th>Description</th><th>Price</th>
<?php 
foreach($result as $row)
 {
?>
<tr><td><?php echo $row->item_number ?></td><td><?php echo $row->description ?></td><td><?php echo number_format($row->price) ?></td></tr>
<?php
}
?>
</div>
<?php
}
?>

Here, I have made home page to show first 10 rows of the table and by specifying row numbers it will list data.

Note*: Create excel according to your DB table and save as->other formats->CSV(Comma delimited).

Download Source
commenter

About Varadharaj V

The founder of Kvcodes, Varadharaj V is an ERP Analyst and a Web developer specializing in WordPress(WP), WP Theme development, WP Plugin development, Frontaccounting(FA), Sales, Purchases, Inventory, Ledgers, Payroll & HRM, CRM, FA Core Customization, OpenCart Theme Development, PHP, HTML, CSS, jQuery, Bootstrap development and content SEO.

Comment Below

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

*

Current ye@r *

Menu

Sidebar

Subscribe E-mail Updates

Congrats, You are Subscribed to Receive Updates.

Advertisement

Category Posts