Insert udpate wordpress post programmatically

This tutorial explains how to insert update wordpress post programmatically. Here it explains how to read data from the CSV file and bulk import content and create the wordpress posts programmatically.

Suppose you are trying add bulk content and images to the wordpress site sometimes it is not practical to create the post from the wordpress admin area. In that case the external script plays a good role.

The external script create the post as shown below.

bulk_insert_update_wordpress_post_programmatically

Here it read the data from the CSV. Please check the sample CSV file image below.The file contain the post title, post content, main parent id, sub page id and two acf fields heading and additional content.

insert_update_wordpress_post_programmatically

Step by step explanation

  • Connect wordpress database
  • Read data from CSV
  • Insert update wordpress post programmatically
  • Set WordPress Featured Image Programmatically

Connect wordpress database

As the first step include the wp-load.php and /wp-admin/includes/taxonomy.php files for the database operations.

require_once 'wp-load.php';
require_once ABSPATH . '/wp-admin/includes/taxonomy.php';
date_default_timezone_set('Europe/London');

Read data from CSV

Please refer the sample CSV file . The data is retrieving from the above file.

function readCSV()
{
    $options_arr = array();
    $images = 'doorsexport.csv';
    $handle = fopen($images, "r");
    $headers = false;
    if (empty($handle) === false) {
        while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
            if (!$headers) {
                $headers[] = $data;
            } else {
                $options_arr[] = $data; 
            }
        }
        fclose($handle);
    }
  
    return $options_arr;
}

Insert update wordpress post programmatically

This step explain how to insert update wordpress post programmatically. Click here for detailed explanation.

function connectDatabase() {
    $mydb = new wpdb('username','password','databasename','localhost');
    return $mydb;
}

function insertUpdatePost($postCSVContents , $mydb) {
    foreach($postCSVContents as $postCSVContent) {
        $parentId = postParent($postCSVContent[3],$postCSVContent[5]);
        $posts_ids[$postCSVContent[0]] =  postExists( $postCSVContent, $posts_ids[$parentId], $mydb );
    }
}

function postParent($mainId , $subId) {
      
    if ( ($subId == '') && ($mainId == '') )
        return 0;
    
    $parentId = ( $subId != '' )? $subId : $mainId ;
    return $parentId;
    
}

function postExists($postCSVContent,$parentId , $mydb) {

    $mydb->get_results($mydb->prepare('SELECT ID FROM `wp_posts` WHERE ID = %d',$postCSVContent[0]));
    
    if( $mydb->num_rows >  0) {
        
        echo 'Post '.$postCSVContent[0].' exist'.PHP_EOL;
        $template_file = get_post_meta( $postCSVContent[0], '_wp_page_template', true );
        echo 'Template File : '.$template_file.PHP_EOL;
        
        $updatePost = array(   
            'ID' => $postCSVContent[0],
            'post_title'    => $postCSVContent['1'],
            'post_content'  => $postCSVContent['2'],
            'post_type' => 'doors',
            'post_status'   => 'publish',
            'post_author'   => 1
        );

        wp_update_post( $updatePost );

        update_post_meta( $postCSVContent[0], '_wp_page_template', $template_file );
        updateAcf( $postCSVContent , $postCSVContent[0] );
  
    }
    else
    {
        echo 'Post '.$postCSVContent[0].' is not existing'.PHP_EOL;        
        echo 'Post parent '.$parentId.PHP_EOL;
        
        $newIds = wp_insert_post( array(
                'post_title' => $postCSVContent['1'],
                'post_content' => $postCSVContent['2'],
                'post_type' => 'doors',
                'post_status' => 'publish',        
                'post_author'   => 1,
                'post_parent' => $parentId
        ));
        
        updateAcf( $postCSVContent , $newIds );
        return $newIds;

    }
    
   
}

Upload Image and Set Featured image Programmatically

The following code upload the image to wordpress media library and set that image as post featured image.

function setFeaturedImages() {
    
    $base = dirname(__FILE__);
    $imgfile= $base.DS.'images'.DS.'14'.DS.'Ascot_Anthracite-Grey-1.jpg';
    $filename = basename($imgfile);
    $upload_file = wp_upload_bits($filename, null, file_get_contents($imgfile));
    if (!$upload_file['error']) {
        $wp_filetype = wp_check_filetype($filename, null );
        $attachment = array(
            'post_mime_type' => $wp_filetype['type'],
            'post_parent' => 0,
            'post_title' => preg_replace('/\.[^.]+$/', '', $filename),
            'post_content' => '',
            'post_status' => 'inherit'
        );
    $attachment_id = wp_insert_attachment( $attachment, $upload_file['file'], 209 );
    
    if (!is_wp_error($attachment_id)) {
        require_once(ABSPATH . "wp-admin" . '/includes/image.php');
        $attachment_data = wp_generate_attachment_metadata( $attachment_id, $upload_file['file'] );
        wp_update_attachment_metadata( $attachment_id,  $attachment_data );
    }
    
    set_post_thumbnail( 209, $attachment_id );
   
    }
}

set_featured_image_wordpress_programmatically

Share this Tutorial

Leave a Reply

Your email address will not be published. Required fields are marked *

*