Create a plugin in wordpress to add Multiple Number of posts, Meta Box And Featured Image from CSV
1. Create a directory with name “csv-upload”.
2. Create files in directory “csv-upload”
a. csv-upload -> csv-upload.php
b. csv-upload -> csv_queryupload.php
c. csv-upload -> ajax-loader.gif
d. csv-upload -> csv //This the directory where csv file upload
csv-upload.php :
<?php
/**
*
Plugin Name: Upload Cause with CSV File
*
Plugin URI: http://websiteurl.com/
*
Description: This plugin helps you to upload Cause with CSV file.
*
Version: 1.0.0
*
Author: Sunil Sharma
*
Author URI: http://websiteurl.com/
*/
$paths = $_SERVER['DOCUMENT_ROOT'];
if(!defined('DS')){
define('DS',DIRECTORY_SEPARATOR);
}
include_once
$_SERVER['DOCUMENT_ROOT'].'/wp-load.php';
function WCM_Setup_Demo_on_activation()
{
if ( ! current_user_can( 'activate_plugins' ) )
return;
}
function WCM_Setup_Demo_on_deactivation()
{
if ( ! current_user_can( 'activate_plugins' ) )
return;
}
function WCM_Setup_Demo_on_uninstall()
{
if ( ! current_user_can( 'activate_plugins' ) )
return;
}
register_activation_hook( __FILE__,
'WCM_Setup_Demo_on_activation' );
//Plugin Activation Hook
register_deactivation_hook( __FILE__,
'WCM_Setup_Demo_on_deactivation' );
//Plugin DeActivation Hook
register_uninstall_hook( __FILE__,
'WCM_Setup_Demo_on_uninstall' );
//Plugin Uninstallation Hook
function video_menu_option(){ ?>
<script
src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script
type="text/javascript">
$(document).ready(function(){
var
singleValues = $("#csv_name").val();
var
ajax_url = "<?php echo
site_url();?>/wp-content/plugins/csv-upload/csv_queryupload.php";
var
dataString = "meta_key=" + singleValues;
$("#MyButton").click(function(){
$('#loader-icon').show();
$.ajax({
type:
'post',
url:
ajax_url,
data:
dataString,
success:
function(responce){
$('#loader-icon').hide();
$('#Success_load').show();
}
});
});
});
</script>
<h1>Upload Multiple Cause with CSV
file</h1>
<form method="post"
enctype="multipart/form-data">
<table>
<tr><td
colspan="2"></td></tr>
<tr><td><strong>Upload
CSV :</strong> </td><td><input type="file"
id="video_link" name="video_link"></td></tr>
<tr><td></td><td><input
type="submit" name="video_submit" value="Upload
CSV"></td></tr>
<tr><td
colspan="2"></td></tr>
</table>
</form>
<?php
if(isset($_POST['video_submit'])){
global
$wpdb;
$name
= $_FILES["video_link"]["name"];
$ext
= end((explode(".", $name))); # extra () to prevent notice
if($ext
== "csv") {
$path
= $_SERVER['DOCUMENT_ROOT'].'/wp-content/plugins/csv-upload/csv/'; //This is the path where CSV upload
$csv_name
= time().$_FILES['video_link']['name'];
$upload_csv
= $path.$csv_name;
}
else {
echo
"Sorry, upload file is not in correct format. Only CSV file upload.";
}
if
(move_uploaded_file($_FILES['video_link']['tmp_name'], $upload_csv)) {
echo
"file is successfully uploaded";
$csv_file
= $upload_csv;
$csvfile
= fopen($csv_file, 'r');
$theData
= fgets($csvfile);
/*
echo "<pre>";
print_r($csvfile);
echo
"</pre>"; */
function
ImportCSV2Array($filename) {
$row
= 0;
$col
= 0;
$handle
= @fopen($filename, "r");
if
($handle)
{
while
(($row = fgetcsv($handle, 4096)) !== false)
{
if
(empty($fields))
{
$fields
= $row;
continue;
}
foreach
($row as $k=>$value)
{
$results[$col][$fields[$k]]
= $value;
}
$col++;
unset($row);
}
if
(!feof($handle))
{
echo
"Error: unexpected fgets() failn";
}
fclose($handle);
}
return
$results;
}
$csvArray
= ImportCSV2Array($csv_file); // This
function read CSV according to first row heading of each column.
$i
= 0;
?>
<table>
<tr><th>Title</th><th>Main
Information</th><th>Sub
Information</th><th>Category</th><th>Currency</th><th>Goal</th><th>Expiry
Date</th><th>Image</th></tr>
<?php
foreach
($csvArray as $csv_array) {
?>
<tr>
<td><?php
echo $csv_array['Title'];?></td>
<td><?php
echo $csv_array['Main Information'];?></td>
<td><?php
echo $csv_array['Sub Information'];?></td>
<td><?php
echo $csv_array['Category'];?></td>
<td><?php
echo $csv_array['Currency'];?></td>
<td><?php
echo $csv_array['Goal'];?></td>
<td><?php
echo $csv_array['Expiry Date'];?></td>
<td><img src="<?php echo $csv_array['Image'];?>" style="width:200px;height:auto;"></td>
</tr>
<?php
$i++;
}
?>
</table>
<div><strong>Click
here to upload Cause in Database</strong><input
type="button" id="MyButton" name="insert_cause"
value="Insert Cause">
<input
type="hidden" value="<?php echo $csv_name;?>"
name="csv_name" id="csv_name">
<div
id="loader-icon" style="display:none;margin-top:
15px;text-align: center;width: 50%;"><img src="<?php echo
site_url();?>/wp-content/plugins/csv-upload/ajax-loader.gif"
/></div>
<div
id="Success_load"
style="display:none;"><strong>All causes is successfully add
in database.</strong></div>
</div>
<?php
}
else {
echo
"Sorry file is not uploaded";
}
}
}
function video_menu () {
add_menu_page('Upload CSV','Upload
CSV','manage_options','video_admin_menu', 'video_menu_option');
}
add_action('admin_menu','video_menu');
?>
csv_queryupload.php :
<?php
require_once("../../../wp-load.php");
$paths = $_SERVER['DOCUMENT_ROOT'];
if(!defined('DS')){
define('DS',DIRECTORY_SEPARATOR);
}
$csv_name = $_POST["meta_key"];
$path = $_SERVER['DOCUMENT_ROOT'].'/wp-content/plugins/csv-upload/csv/'; // Read Uploaded CSV from this path
//$csv_name = $csv_name;
$upload_csv = $path.$csv_name;
$csv_file = $upload_csv;
$csvfile = fopen($csv_file, 'r');
$theData = fgets($csvfile);
function ImportCSV2Array($filename) {
$row = 0;
$col = 0;
$handle = @fopen($filename, "r");
if ($handle)
{
while (($row = fgetcsv($handle, 4096)) !== false)
{
if (empty($fields))
{
$fields = $row;
continue;
}
foreach ($row as $k=>$value)
{
$results[$col][$fields[$k]] = $value;
}
$col++;
unset($row);
}
if (!feof($handle))
{
echo "Error: unexpected fgets() failn";
}
fclose($handle);
}
return $results;
}
$csvArray = ImportCSV2Array($csv_file);
$i = 0;
foreach ($csvArray as $csv_array) {
$project_title = $csv_array['Title']; // Read Column with "Title" heading
$project_story = $csv_array['Main Information']; // Read Column with "Main Information" heading
$sub_info = $csv_array['Sub Information']; // Read Column with "Sub Information" heading
$project_categories = $csv_array['Category']; // Read Column with "Category" heading
$project_currency = $csv_array['Currency']; // Read Column with "Currency" heading
$project_amount = $csv_array['Goal']; // Read Column with "Goal" heading
$expiry_date = $csv_array['Expiry Date']; // Read Column with "Expiry Date" heading
$old_date = $expiry_date;
$old_date_timestamp = strtotime($old_date);
$project_date = date(get_option('date_format'), $old_date_timestamp);
$project_image = $csv_array['Image']; // Read Column of featured image with "Image" heading
$post_information = array(
'post_title' => esc_attr(strip_tags($project_title)),
'post_content' => esc_attr(strip_tags($project_story)),
'post_type' => 'project',
'post_author' => $current_user->ID,
'post_status' => 'publish',
);
$post_information['post_status'] = "publish";
$post_id = wp_insert_post($post_information);
if($post_id) {
$thepostid = $post_id;
if ($project_categories) {
$test = wp_set_object_terms($post_id, $project_categories, 'project-category' );
}
if ($project_currency!='') { $project_settings['currency'] = $project_currency; }
if ($project_date!='') { $project_settings['date'] = $project_date; }
if ($project_amount!='') { $project_settings['target'] = $project_amount; }
add_post_meta($post_id, 'settings', $project_settings, true);
add_post_meta($post_id, 'datum', $project_settings['date']);
add_post_meta($post_id, 'bereiding', $sub_info);
if($project_image!='') {
//echo $project_image;
echo $image_url = $project_image;
//echo $image_url = site_url().'/wp-content/uploads/2015/03/image1.png';
$upload_dir = wp_upload_dir(); // Set upload folder
$image_data = @file_get_contents($image_url); // Get image data
/* function curl($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
return curl_exec($ch);
curl_close($ch);
} */
//echo $image_data = curl($image_url);
$filename = basename($image_url); // Create image file name
if( wp_mkdir_p( $upload_dir['path'] ) ) {
$file = $upload_dir['path'] . '/' . $filename;
} else {
$file = $upload_dir['basedir'] . '/' . $filename;
}
//$file = $upload_dir['path'] . '/' . $filename;
file_put_contents($file,$image_data);
//echo $file = $file;
// Check image file type
$wp_filetype = wp_check_filetype( $filename, null );
// Set attachment data
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => sanitize_file_name( $filename ),
'post_content' => '',
'post_status' => 'inherit'
);
// Create the attachment
$attach_id = wp_insert_attachment( $attachment, $file, $post_id );
// Include image.php
require_once(ABSPATH . 'wp-admin/includes/image.php');
// Define attachment metadata
$attach_data = wp_generate_attachment_metadata( $attach_id, $file );
// Assign metadata to attachment
wp_update_attachment_metadata( $attach_id, $attach_data );
// And finally assign featured image to post
set_post_thumbnail( $post_id, $attach_id );
add_post_meta($post_id, '_thumbnail_id', $attach_id);
}
}
$i++;
}
//echo $name_csv;
?>
ajax-loader.gif :
CSV Format :
Be shure the image is exist on given image Url
in CSV, otherwise featured image is not create for post.
CSV
data is read according to first row heading of csv like Title, Main
Information, Sub Information, Category, Currency, Goal, Expiry Date,
Image. If you want to change this
heading, then also change in code, otherwise data is not read of this row.
How
to use this plugin
Upload CSV according to instruction on
given attachment image.
Be shure the image is exist on given image Url
in CSV, otherwise featured image is not create for post.
CSV
data is read according to first row heading of csv like Title, Main
Information, Sub Information, Category, Currency, Goal, Expiry Date,
Image. If you want to change this
heading, then also change in code, otherwise data is not read of this row.



No comments:
Post a Comment