CSV Post Upload

When you are in hurry and you need to publish a huge amount of post to your WordPress sites from an Excel sheet then what will you do? I think copy the data from the Excel sheet over and over is tiresome and lengthy process. So I have a solution for that situation which may solve the problem in a while. Today we will learn how to create one.

First of all create an admin page and add it to the functions.php file of your WordPress site.


defined('ABSPATH') or die("Cannot access pages directly.");
if ( is_admin() && is_user_logged_in() ) {
    add_action('admin_menu', 'post_upload_menu');
}
function post_upload_menu(){

    add_menu_page( 'Post Upload', 'Post Upload', 'manage_options', 'file-upload', 'upload_func',get_template_directory_uri().'/images/upload.png' );
}

 

Now a blank page is created on your admin panel. Now It’s time to add a form for uploading a csv file and read data from it.

Add the below code under the above portion of the page.


function upload_func() {

    upload_post();
echo '

 

Post Content Upload

 

‘; submit_button(‘Upload & Import’); echo ‘

‘; }

 

Below  you can see a method named upload_post() where the main work of the file uploading and writing to the WordPress database will occur. The function first executes when the submit button is pressed.

First the function checks for the uploaded file extension for validation of the file. If the file is not a csv file then it shows an error. The file is uploaded by the function media_file_upload which handles the post requests of the file upload.

We then create a directory under the upload directory of the WordPress folder.  If it doesn’t exist then we will create it automatically. Then we will save the uploaded file in the directory and open the file through php file function. Now we will read from the csv file row and add the content from the row to the WordPress post by wp_insert_post() method. We can also update post meta field and category and everything we want.

Paste the below code after the above code.


function upload_post(){
// First check if the file appears on the _FILES array
if(isset($_FILES['upload_files'])) {

$csv = $_FILES['upload_files'];
$allowed =  array('csv');
$filename = $_FILES['upload_files']['name'];
$ext = pathinfo($filename, PATHINFO_EXTENSION);

if(!in_array($ext,$allowed) ) {
echo '

Not a valid file format. Please Upload .csv file...

‘; } else { $uploaded=media_handle_upload(‘upload_files’, 0); if( is_wp_error( $uploaded ) ) { echo ‘

Error uploading file: ‘ . $uploaded->get_error_message().’

‘; } else { echo ‘

File upload successful!

‘; $id = $uploaded; $file = get_post($id); $contents=file_get_contents(wp_get_attachment_url($id)); $upload_dir = wp_upload_dir(); $outputdir = preg_replace( “[\\/]”, DIRECTORY_SEPARATOR, $upload_dir[‘basedir’] ) . “\upload_files”.DIRECTORY_SEPARATOR; $outputdir = ABSPATH.’wp-content/uploads/upload_files/’; if (!file_exists($outputdir)) { mkdir($outputdir, 0777, true); } try { // This method is very improtant as it allows us access to the file system WP_Filesystem(); // Write output $file_name = $outputdir.$file->post_title.”.csv”; file_put_contents( $file_name, $contents ); $row = 0; if ( $file_name ) { $handle = fopen( $file_name, “r” ); while ( ( $data = fgetcsv($handle, 1000, “,” )) !== FALSE ) { $row ++; if($row == 1) continue; if ( $data[1] == ” ) { $content = ”; } else { $content = utf8_uri_encode( ‘

  • ‘.str_replace( array(“\r”,”\n\n”,”\n” ),array( ”,”\n”,”

\n

  • ” ),trim( str_replace(‘?’, ”, $data[1]),”\n\r” ) ).’

‘ ); } $add_new_post = array( ‘post_title’ => utf8_uri_encode( $data[0] ), ‘post_content’ => $content, ‘post_status’ => ‘publish’, ‘post_type’ => ‘test-products’ ); $the_post_id = wp_insert_post( $add_new_post ); update_post_meta( $the_post_id, ‘meta_field_1’, $data[2] ); } fclose( $handle ); echo ‘

‘.(int)($row-1).’ Post Uploaded.

‘; } } catch (Exception $e){ echo ‘

‘.$e->getMessage() . ‘

‘; return; } } } } }

 

Hope this helped a little.

Saniul Ahsan

I picked PHP and JavaScript as a career start-up and developed a lot of applications using these. Like Management Application, Web Scrapping, Web API, E-Commerce Solutions, Finance Application etc. Outside of my professional life, I also do projects and code for reputation and my personal portfolio.