How can I get an image from the uploads dir and enter it in the media library?

I want to develop a script that:

  1. Gets an image from a post’s content and removes it (it’s hosted on another website)
  2. Uploads it in the uploads directory
  3. Adds it in the media library and
  4. Lastly returns the content with the image saved on server.

I can’t make the third step.
The problem is with wp_insert_attachment, every time it’s run inside a function called by add_filter, either apache returns "PHP Fatal error: Allowed memory size" (my php memory limit is 124MB) or the page keeps loading forever.

Read More

The same problem doesn’t occur when wp_insert_attachment runs outside of a function called by add_filter. I cannot put it outside though because I want to feed it with the $image_path data received from download_image function.

I also tried calling a separate function that does step 3, run from inside of download_image function, with $image_path passed as a variable but the same problem occurred. Why that happens, any ideas on how to solve it?

add_filter('content_save_pre', 'download_image');

function download_image($content_save_pre) 
{
    preg_match( '/<img[^<]+>/i', $content_save_pre, $result ); // Find first image with tags
    $image_tags = $result[0]; // Save image with tags
    $content_save_pre = str_replace( $image_tags, '', $content_save_pre ); // Remove image with tags
    preg_match( '/http[^"]+/i', $result[0], $result ); // Find URL  
    $url_only = $result[0];  

    preg_match( '/[^/]+$/i', $result[0], $result ); // Find filename
    $filename = $result[0];
    $uploads = wp_upload_dir(); // Find Upload dir path
    $uploads_path = $uploads['path'];
    $uploads_url = $uploads['url'];

    $image = file_get_contents( $url_only ); // Save image in uploads folder  
    file_put_contents( $uploads_path . '/' . $filename, $image );

    $image_url = $uploads_url . '/' . $filename; // URL of the image on the disk
    $image_path = $uploads_path . '/' . $filename; // Path of the image on the disk

    // Add image in the media library - Step 3

    $wp_filetype = wp_check_filetype( basename( $image_path ), null );
    $attachment = array(
       'post_mime_type' => $wp_filetype['type'],
       'post_title'     => preg_replace( '/.[^.]+$/', '', basename( $image_path ) ),
       'post_content'   => '',
       'post_status'    => 'inherit'
    );

    $attach_id = wp_insert_attachment( $attachment, $image_path );  
    require_once( ABSPATH . 'wp-admin/includes/image.php' );
    $attach_data = wp_generate_attachment_metadata( $attach_id, $image_path );
    wp_update_attachment_metadata( $attach_id, $attach_data );

    return '<img src="' . $image_url . '"/>' . $content_save_pre; // Return content with the image saved on server
}

Might that be a bug or something. Should I report it?

Related posts

Leave a Reply