wp upload Single image

$user_id = get_current_user_id();

<?php 
$title     = $_POST['title'];
$content   = $_POST['content'];
//$custom_field = $_POST['custom_1']; 
$post_type = 'portfolio';


//the array of arguements to be inserted with wp_insert_post
$new_post = array(
'post_title'    => $title,
'post_content'  => $content,
'post_status'   => 'publish',         
'post_type'     => 'portfolio',
'post_author'   => $user_id,
);

//insert the the post into database by passing $new_post to wp_insert_post
//store our post ID in a variable $pid
//we now use $pid (post id) to help add out post meta data
 $pid=wp_insert_post($new_post);
 if($pid  < 0){
        echo "Error Occured.";
    }else{

   $filename = $_FILES['featured_image']['name'];
  $wp_filetype = wp_check_filetype( basename($filename), null );
  $wp_upload_dir = wp_upload_dir();

  // Move the uploaded file into the WordPress uploads directory
  move_uploaded_file( $_FILES['featured_image']['tmp_name'], $wp_upload_dir['path']  . '/' . $filename );

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

  $filename = $wp_upload_dir['path']  . '/' . $filename;

  $attach_id = wp_insert_attachment( $attachment, $filename, $attach_id);
  require_once( ABSPATH . 'wp-admin/includes/image.php' );
  $attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
  wp_update_attachment_metadata( $attach_id, $attach_data );
  update_post_meta($pid, '_thumbnail_id', $attach_id);
} ?>

Leave a comment