As a site owner you will often find yourself in situations where you have to import large datasets. It can be incredibly useful to know how to create posts programmatically in WordPress.

Arrays are a great way to store data, but when you are dealing with multi-dimensional arrays (an array inside an array) then you have to loop through both arrays, which can decrease peformance, but since we only want to use this to import data and not use it on the fly, we’re good.

Loop Through Files With Content (Skip If Doesn’t Apply)

If you want to loop through various files stored on your hard drive like text files or XML files, we can do this:

 foreach($files as $file) { 
print_r($file);  echo "---------------------";
$lines = file(__DIR__ . '/files/'.$file);
$keys = explode('^', array_shift($lines));
$results = array_map(
    function($x) use ($keys){
        return array_combine($keys, explode('^', trim($x)));

Loop Through Arrays

So let’s take a look at the code to loop through our array:

If you want to flatten the multidimension array you can do this, but I prefer using two loops instead.

$result = array_flatten($results);

Using two foreach loops allows you to quickly retrieve each value stored in the multi-dimensional array. I added some echos for easier debugging purposes, this should help you see what the loop is retrieving.

 foreach($results as $key => $value){
              foreach( $value as $key2 => $value2){
               $first = array_values($results[0]) ;
               $comma_separated = ltrim(str_replace(":", " ", strstr(implode(",", $first), ':', false)),' ');
                $property = strstr($value2, ':', true);
                $option = str_replace(":", " ",strstr($value2, ':', false)) ;
                echo "$option\n
\n"; $option2 = ltrim($option, ' '); /*** CODE TO IMPORT DATA AS POSTS; SEE BELOW ***/ } }

Trimming Input: Removing Spaces

Please note, I am stripping some spaces from the lines I retrieved from my text files. You probably don’t have to do that depending on your files.

$option2 = ltrim($option, ' ');

Importing The Data As Posts

The following code will allow you to import the data. You have to specify $authorid first. $option in my case is the filename.

$postsql = array(	
            'post_author'=> $authorid, 
            'post_date'=> date('Y-m-d H:i:s'),
            'post_date_gmt' => date('Y-m-d H:i:s'),
            'post_content' => ' ',
            'post_title' => 'My Post: '.ltrim($option), 
            'post_excerpt' => ' ',
            'post_status' => 'publish',
            'comment_status' => 'open',
            'ping_status' => 'open',
            'post_name' => ltrim(str_replace(".", "-",$option),' '), 
            'post_modified' => date('Y-m-d H:i:s'),
            'post_modified_gmt' => date('Y-m-d H:i:s'),
            'post_parent' => 0,
            'post_type' => 'post',
            'menu_order' => 0

Let’s take it one step further. We also need to upload some attachments:

$filetype = wp_check_filetype( basename( $filename ), null );
$wp_upload_dir = wp_upload_dir();

 $attachment = array(
                'guid'           => $wp_upload_dir['url'] . '/' . basename( $filename ), 
                'post_mime_type' => $filetype['type'],
                'post_title'     => preg_replace( '/\.[^.]+$/', '', basename( $filename ) ),
                'post_content'   => '',
                'post_status'    => 'inherit'
$attachment_id = wp_insert_attachment( $attachment, $filename, $id )

There’s a bunch of other stuff you can do like changing categories and updating custom fields. The options are endless.

Now use this to create something fancy. Good luck!