Created
January 11, 2013 07:22
-
-
Save ankitnetwork18/4508683 to your computer and use it in GitHub Desktop.
wordpress: api for importing data from text file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
* This is wordpress API for importing data from text file | |
* http://localhost/sandbox/wordpress/wp-content/plugins/data_import/import_data.php | |
*/ | |
//load wordpress functions | |
require_once("../../../wp-load.php"); | |
//path of text file from where posts need to be imported | |
$data_file = 'data.txt'; | |
//get the contents of data file | |
if(file_exists($data_file)) | |
$data = file_get_contents($data_file); | |
$isvalidFile = false; | |
$inserted_post_ids = array(); | |
if( gettype($data) == 'string' && strstr($data,'~~') && strstr($data,'!!##!!') ){ | |
$isvalidFile = true; | |
} | |
if($isvalidFile) { | |
$posts = explode('!!##!!', $data); | |
$posts = array_filter($posts, 'trim'); | |
foreach($posts as $post) { | |
//get data form text file | |
list($post_title,$post_content,$post_type) = explode('~~', $post); | |
$post_date = '2012-12-01 00:00:00'; | |
$post_date_gmt = "2012-12-01 00:00:00"; | |
$post_name = sanitize_title($post_title); | |
//prepare the post array to be inserted in db | |
$this_post = array( | |
'post_title' => $post_title, | |
'post_content' => $post_content, | |
'post_status' => 'publish', | |
'post_author' => 1, | |
'post_date' => $post_date, | |
'post_date_gmt' => $post_date_gmt, | |
'post_name' => $post_name | |
); | |
//insert the post data | |
$result = wp_insert_post($this_post); | |
//grab the inserted post id & add meta data related with post | |
if($result>0) { | |
$inserted_post_id = $result; | |
//add all post meta info | |
add_post_meta( $inserted_post_id, 'content_type', $post_type ); | |
//update the list of inserted post ids | |
$inserted_post_ids[] = $inserted_post_id; | |
} | |
} | |
} | |
//if the records inserted, display list of post ids inserted | |
if(count($inserted_post_ids)>0){ | |
echo "<ol>"; | |
foreach($inserted_post_ids as $post_id){ | |
echo "<li> Post inserted with id: $post_id </li>"; | |
} | |
echo "</ol>"; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment