Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
    Posts
  • #1461189
    Jonathon Parris
    Guest

    hello,

    I’m trying to set the featured image from first image URL in my posts. Can you help me? I seem to be missing something.

    #1461277

    Hey Jonathon Parris,

    Thank you for the inquiry.

    You can try the following code in the functions.php file. It should work for both the actual URL and the image element.

    
    function av_auto_set_featured_image($post_id) {
        if (wp_is_post_autosave($post_id) || wp_is_post_revision($post_id)) {
            return;
        }
    
        if (has_post_thumbnail($post_id)) {
            return;
        }
    
        $post = get_post($post_id);
        $content = $post->post_content;
    
        $image_url = '';
    
        if (preg_match('/<img.*?src=["\'](https?:\/\/.*?\.(jpg|jpeg|png|gif))["\']/', $content, $matches) || preg_match('/(https?:\/\/.*?\.(jpg|jpeg|png|gif))/', $content, $matches)) {
            $image_url = $matches[1];
        }
    
        if ($image_url) {
            $attachment_id = insert_attachment_from_url($image_url, $post_id);
            if ($attachment_id) {
                set_post_thumbnail($post_id, $attachment_id);
            }
        }
    }
    add_action('save_post', 'auto_set_featured_image');
    
    function av_insert_attachment_from_url($url, $post_id) {
        $temp_file = download_url($url);
        if (is_wp_error($temp_file)) {
            return false;
        }
    
        $file = array(
            'name'     => basename($url),
            'type'     => mime_content_type($temp_file),
            'tmp_name' => $temp_file,
            'error'    => 0,
            'size'     => filesize($temp_file),
        );
    
        $sideload = wp_handle_sideload($file, array('test_form' => false));
        if (!empty($sideload['error'])) {
            @unlink($temp_file);
            return false;
        }
    
        $attachment = array(
            'post_mime_type' => $sideload['type'],
            'post_title'     => sanitize_file_name($file['name']),
            'post_content'   => '',
            'post_status'    => 'inherit',
        );
    
        $attachment_id = wp_insert_attachment($attachment, $sideload['file'], $post_id);
    
        require_once(ABSPATH . 'wp-admin/includes/image.php');
        $attach_data = wp_generate_attachment_metadata($attachment_id, $sideload['file']);
        wp_update_attachment_metadata($attachment_id, $attach_data);
    
        return $attachment_id;
    }
    

    Best regards,
    Ismael

Viewing 2 posts - 1 through 2 (of 2 total)
  • You must be logged in to reply to this topic.