Learn how to programmatically set a featured image for WordPress posts and pages using PHP.
<?php
require_once("../wp-load.php");
$postId = '5342';
$IMGFileName = 'turkey.png';
$dirPath = getcwd();
$IMGFilePath = $dirPath.'/'.$IMGFileName;
$message = $IMGFileName.' is not available or found in directory.';
if(file_exists($IMGFileName)){
$upload = wp_upload_bits($IMGFileName , null, file_get_contents($IMGFilePath, FILE_USE_INCLUDE_PATH));
$imageFile = $upload['file'];
$wpFileType = wp_check_filetype($imageFile, null);
$attachment = array(
'post_mime_type' => $wpFileType['type'],
'post_title' => sanitize_file_name($imageFile),
'post_content' => '',
'post_status' => 'inherit'
);
$attachmentId = wp_insert_attachment( $attachment, $imageFile, $postId );
$attachmentData = wp_generate_attachment_metadata( $attachmentId, $imageFile);
wp_update_attachment_metadata( $attachmentId, $attachmentData );
$success = set_post_thumbnail( $postId, $attachmentId );
if($success){
$message = $IMGFileName.' has been added as featured image to post.';
} else {
$message = $IMGFileName.' has NOT been added as featured image to post.';
}
}
echo $message;
?>