How to Import Posts from a Text File into WordPress

Here is a simple method that you can use to import news, posts or content from a text file into WordPress. This script assumes the text data file has each post on a separate line with fields separated by a |. This is how most flat file news scripts store data. It also uses the php tidy extension to clean the input before inserting into the database. If you need to import data from a different source, all you need to do is include the wp-load.php script and use wp_insert_post to insert post.

define('MY_WP_PATH', 'path/to/directory');
define('CUTENEWS_FILE', 'path/to/news.txt');
require_once( MY_WP_PATH . '/wp-load.php' );
$all_news = array_reverse(file(CUTENEWS_FILE));
$tidy_config = array(
    'indent' => TRUE,
    'output-xhtml' => TRUE,
'drop-font-tags' => 'yes',
'drop-empty-paras' => 'yes',
'quote-ampersand' => 'yes',
'quote-marks' => 'yes',
'drop-proprietary-attributes' => 'yes',
'logical-emphasis' => 'yes',
'show-body-only' => TRUE,
'wrap' => 0,
$user_ID = 1;
foreach ($all_news as $news) {
list($date, $author, $title, $short_story, $full_story, $avatar) = explode('|', $news);
$tidy = tidy_parse_string($title, $tidy_config, 'ascii');
$title = $tidy;
$story = empty($full_story) ? $short_story : $full_story;
$story = str_replace('{nl}', '', $story); // remove new line tag from cute news
$tidy = tidy_parse_string($story, $tidy_config, 'ascii');
$story = $tidy;
$story = preg_replace('#<p>\s*&nbsp;\s*</p>#im', '', $story); // remove empty paragraphs
    $new_post = array(
        'post_title'    => $title,
        'post_content'  => $story,
        'post_status'   => 'publish',
        'post_date'     =>date('Y-m-d H:i:s', $date),
        'post_author'   => $user_ID,
        'post_type'     => 'post',
        'post_category' =>array(0)
    $post_id = wp_insert_post($new_post);
echo $post_id . '<br>';