I need to insert post programatically in wordpress.. I finished to insert title and content.. But image is not uploaded and attached.. Can you suggest me..
$post_id = wp_insert_post( array( 'post_author' => $user->ID, 'post_title' => $Title, 'post_content' =>$Content, 'post_status' => 'publish', 'post_type' => 'post', 'guid' => $site_url . '/?p=' . $post_id ) ); $Featured_image = http://ecx.images-amazon.com/images/I/51l-rEon-NL._SL110_.jpg; $year = date("Y"); $month = date("m"); $url = '/wp-content/uploads/'. $year . '/' . $month . '/' . basename($Featured_image); // Check the type of file. We'll use this as the 'post_mime_type'. $filetype = wp_check_filetype( basename( $Featured_image ), null ); // Get the path to the upload directory. $wp_upload_dir = wp_upload_dir(); // Prepare an array of post data for the attachment. $attachment = array( 'guid' => $wp_upload_dir['url'] . '/' . basename( $Featured_image ), 'post_mime_type' => $filetype['type'], 'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $Featured_image )), 'post_content' => '', 'post_status' => 'inherit', 'post_type' => 'attachment' ); // Insert the attachment. $attach_id = wp_insert_attachment( $attachment, $year . '/' . $month . '/' . basename($Featured_image) , $post_id ); require_once( ABSPATH . 'wp-admin/includes/image.php' ); $attach_data = wp_generate_attachment_metadata( $attach_id, $url ); wp_update_attachment_metadata( $attach_id, $attach_data ); set_post_thumbnail( $post_id, $attach_id );
I tried this, but image is displaying in media like this,
At the same time, Image is not storing in uploads folder.. I dont know how to fix this issue.. Can anyone suggest me..