PHP Developer

Friday, 19 August 2016

How Featured Image Assign and upload for Post(By Post ID)

How Featured Image Assign and upload for Post(By Post ID):

<?php
$post_id = $post_id; //post id for which featured image upload
$uploaddir = wp_upload_dir();
$selected_postImage = $_FILES["files"]["name"];
$project_postImage = $uploaddir['path'] . '/' . $selected_postImage;
if ($selected_postImage != '') {
    $filename   = basename($project_postImage);
    $wp_filetype = wp_check_filetype( $project_postImage, null );
    $attachment = array(
         'post_mime_type' => $wp_filetype['type'],
         'post_title'     => sanitize_file_name( $filename ),
         'post_content'   => '',
         'post_status'    => 'inherit'
    );
    $attach_id = wp_insert_attachment( $attachment, $project_postImage, $post_id );
   
    require_once(ABSPATH . 'wp-admin/includes/image.php');
   
    $uploadfile = $uploaddir['path'] . '/' . $filename;
    move_uploaded_file( $_FILES['files']['tmp_name'] , $uploadfile );
    $attach_data = wp_generate_attachment_metadata( $attach_id, $project_postImage );
    wp_update_attachment_metadata( $attach_id, $attach_data );
    set_post_thumbnail( $post_id, $attach_id );
}
?>

No comments:

Post a Comment