Search code examples
phpwordpressfile-get-contentsfile-put-contentswordpress-featured-image

file_put_contents is not saving remote image to local folder in a WordPress plugin


In my WordPress v6.1.1, I have a custom plugin with form. This plugin creates a custom post-type post. This post will have a featured image which should be updated from a remote URL, with below code:

$wp_post_id = wp_insert_post($post_data); // creates new custom post >> successful

    if (!is_wp_error($wp_post_id)) {

        // require once for image upload
        require_once(ABSPATH . 'wp-admin/includes/media.php');
        require_once(ABSPATH . 'wp-admin/includes/file.php');
        require_once(ABSPATH . 'wp-admin/includes/image.php');

        $image_url = 'https://media-exp1.licdn.com/dms/image/C4E0BAQHd5Km8_W6GVA/company-logo_200_200/0/1614178926580?e=2159024400&v=beta&t=yS_l9a36Xy5HHt8dnKIAWsoPo2OHgbxI18r0qNOrH-0'; // URL
        $image_save_path = WP_CONTENT_DIR . '/logos/' . sanitize_title('Post Title') . '.jpg'; // local folder filename path
        file_put_contents($image_save_path, file_get_contents($image_url)); // save to local folder

        $logo_url = content_url() . '/logos/' . sanitize_title('Post Title') . '.jpg';
        $logo_load = media_sideload_image($logo_url, $wp_post_id, 'Post Title', 'id');
        set_post_thumbnail($wp_post_id, $logo_load);
    }

This code perfectly works in the theme file while testing, but not within the plugin file.php. It is failing at file_put_contents itself as I did not see any images copied to wp-content\logos folder.


Solution

  • It was the empty URLs causing the issue and validating the image URL solved the issue. Below the updated code:

    $wp_post_id = wp_insert_post($post_data); // creates new custom post >> successful
    
    if ((!is_wp_error($wp_post_id)) && (filter_var($image_url_from_form, FILTER_VALIDATE_URL))) {
    
        // require once for image upload
        require_once(ABSPATH . 'wp-admin/includes/media.php');
        require_once(ABSPATH . 'wp-admin/includes/file.php');
        require_once(ABSPATH . 'wp-admin/includes/image.php');
    
        $image_url = $image_url_from_form; // URL defined in the form that created the $wp_post_id
        $image_save_path = WP_CONTENT_DIR . '/logos/' . sanitize_title('Post Title') . '.jpg'; // local folder filename path
        file_put_contents($image_save_path, file_get_contents($image_url)); // save to local folder
    
        $logo_url = content_url() . '/logos/' . sanitize_title('Post Title') . '.jpg';
        $logo_load = media_sideload_image($logo_url, $wp_post_id, 'Post Title', 'id');
        set_post_thumbnail($wp_post_id, $logo_load);
    }