phpwordpress

How to programmatically upload image to the wordpress and set it as featured image?


Here, In this functions.php file what i am trying to do is I am fetching the image from my post content actually i am using the image_url in content ( This part of fetching the first image is working fine , I have tested it ) . The problem is that i can't upload the image using the url and set it as a featured_image getting the ' published failed ' popup. Anyone can you help me out , or if you have another way ?

function generate_post_featured_image($post_ID) {
$post = get_post($post_ID);

if (empty($post->featured_image)) {
    // Find the first image URL in the post content
    preg_match('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
    if (isset($matches[1])) {
        $image_url = $matches[1];

        // Sideload the image and get the attachment ID
        $attachment_id = media_sideload_image($image_url, $post_ID, null, 'id');

        if (!is_wp_error($attachment_id) && !empty($attachment_id)) {
            // Set the attachment ID as the featured image
            set_post_thumbnail($post_ID, $attachment_id);
        } else {
            $error_message = $attachment_id->get_error_message();
            echo 'Error sideloading image: ' . $error_message;
        }
    }
}
}

add_action('publish_post', 'generate_post_featured_image');

enter image description here


Solution

  • function upload_image_and_set_featured($post_ID) {
        $post = get_post($post_ID);
    
        if (empty($post->featured_image)) {
            // Find the first image URL in the post content
            preg_match('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
            if (isset($matches[1])) {
                $image_url = $matches[1];
    
                // Upload the image and get the attachment ID
                $upload_dir = wp_upload_dir();
                $image_data = file_get_contents($image_url);
                $filename = basename($image_url);
                if (wp_mkdir_p($upload_dir['path'])) {
                    $file = $upload_dir['path'] . '/' . $filename;
                } else {
                    $file = $upload_dir['basedir'] . '/' . $filename;
                }
                file_put_contents($file, $image_data);
                $wp_filetype = wp_check_filetype($filename, null);
                $attachment = array(
                    'post_mime_type' => $wp_filetype['type'],
                    'post_title' => sanitize_file_name($filename),
                    'post_content' => '',
                    'post_status' => 'inherit'
                );
                $attachment_id = wp_insert_attachment($attachment, $file, $post_ID);
                if (!is_wp_error($attachment_id)) {
                    require_once(ABSPATH . 'wp-admin/includes/image.php');
                    $attachment_data = wp_generate_attachment_metadata($attachment_id, $file);
                    wp_update_attachment_metadata($attachment_id, $attachment_data);
                    set_post_thumbnail($post_ID, $attachment_id);
                } else {
                    $error_message = $attachment_id->get_error_message();
                    echo 'Error uploading image: ' . $error_message;
                }
            }
        }
    }
    
    add_action('publish_post', 'upload_image_and_set_featured');
    

    Add the above code in your function.php. this code takes the first image from your content and set it in the featured image.