Include wp load file in your php script file:

require_once("../../wp-load.php");

Add below script to insert post as well as its featured image programmatically.



    $new_post = array(
        'post_title' => $title, 
        'post_content' => $content,
        'post_status' => 'publish',
       // 'post_date' => date('Y-m-d H:i:s'),
        'post_author' => 1,
        'post_type' => 'post',
        'post_category' => array(0)
        );


    if (!get_page_by_title($title, 'OBJECT', 'post') ){

       $post_id = wp_insert_post($new_post);

      /* wp_insert_attachment */
      $filetype = wp_check_filetype( basename( $imagePath ), null );
      $wp_upload_dir = wp_upload_dir();
      $attachment = array(
          'guid'           => $wp_upload_dir['url'] . '/' . basename( $imagePath ), 
          'post_mime_type' => $filetype['type'],
          'post_title'     => preg_replace( '/\.[^.]+$/', '', basename( $imagePath ) ),
          'post_content'   => '',
          'post_status'    => 'inherit'
      );
      $attach_id = wp_insert_attachment( $attachment, $imagePath, $post_id );
      require_once( ABSPATH . 'wp-admin/includes/image.php' );
      $attach_data = wp_generate_attachment_metadata( $attach_id, $imagePath );
      wp_update_attachment_metadata( $attach_id, $attach_data );
      set_post_thumbnail( $post_id, $attach_id );
     
    }

Leave a comment