Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Upload media file from external URL to WordPress Media Library

Tags:

wordpress

I want to upload a file from external URL to the WordPress Media Library (that is common to ALL POSTS/PAGES). The return value I want to get is attachment ID in order to inject them into a shortcode (e.g. img).

I tried using IMEDIA_HANDLE_SIDELOAD but I got lost with $_FILES settings.

However, I am not sure about the parameters:

  • Is this the right function?
  • where in the code (aFile) should I place the URL I want to download from?
  • What is the "tmp_name" and "name"?

See my code:

    // my params
    $post_id = 0; // is this what makes it common to all posts/pages?
    $url = 'www.some_external_url.com/blabla.png';

    // example from some forum
    $filepath = '/relative/path/to/file.jpg';
    $wp_filetype = wp_check_filetype( basename( $filepath ), null );
    $aFile["name"] = basename( $filepath );
    $aFile["type"] = $wp_filetype;
    $afile["tmp_name"] = $filepath;

    $attach_id = $media_handle_sideload( $aFile, $post_id, 'sometitle' );
like image 200
Nizar Blond Avatar asked Sep 06 '25 03:09

Nizar Blond


1 Answers

Solution:

private function _uploadImageToMediaLibrary($postID, $url, $alt = "blabla") {

    require_once("../sites/$this->_wpFolder/wp-load.php");
    require_once("../sites/$this->_wpFolder/wp-admin/includes/image.php");
    require_once("../sites/$this->_wpFolder/wp-admin/includes/file.php");
    require_once("../sites/$this->_wpFolder/wp-admin/includes/media.php");

    $tmp = download_url( $url );
    $desc = $alt;
    $file_array = array();

    // Set variables for storage
    // fix file filename for query strings
    preg_match('/[^\?]+\.(jpg|jpe|jpeg|gif|png)/i', $url, $matches);
    $file_array['name'] = basename($matches[0]);
    $file_array['tmp_name'] = $tmp;

    // If error storing temporarily, unlink
    if ( is_wp_error( $tmp ) ) {
        @unlink($file_array['tmp_name']);
        $file_array['tmp_name'] = '';
    }

    // do the validation and storage stuff
    $id = media_handle_sideload( $file_array, $postID, $desc);

    // If error storing permanently, unlink
    if ( is_wp_error($id) ) {
        @unlink($file_array['tmp_name']);
        return $id;
    }

    return $id;
}
like image 81
Nizar Blond Avatar answered Sep 08 '25 00:09

Nizar Blond