Insert update wordpress post programmatically

This tutorial explains how to create update wordpress post programmatically. Here it shows how to read data from the CSV and create wordpress post dynamically at one go. Please refer the tutorial how to read data from the following CSV.

insert_update_wordpress_post_programmatically

The insertUpdatePost() function iterate through the array and the postparent() function find the parent page based on the subpage_Id and the mainparent_id. Function postExists() check whether the id exist or not based on that it update or create the post accordingly.

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;

    }
    
   
}

Share this Tutorial