Skip to content

Instantly share code, notes, and snippets.

@hasinur1997
Last active September 19, 2022 15:13
Show Gist options
  • Save hasinur1997/fc552296cbffa583a18e44b3139b59c8 to your computer and use it in GitHub Desktop.
Save hasinur1997/fc552296cbffa583a18e44b3139b59c8 to your computer and use it in GitHub Desktop.
WordPress Media upload using wp-media

WP Media Upload

https://dev.to/kelin1003/utilising-wordpress-media-library-for-uploading-files-2b01

(function($){
    /**
     * [uploadButton description]
     *
     * @param   {[type]}  #upload_photo  [#upload_photo description]
     *
     * @return  {[type]}                 [return description]
     */
    let uploadButton = $('#upload_photo');
    
    /**
     * Image container
     *
     * @param   {[type]}  #image-container  [#image-container description]
     *
     * @return  {[type]}                    [return description]
     */
    let imageContainer = $('#image-container');

    /**
     * [media description]
     *
     * @return  {[type]}  [return description]
     */
    let uploadMedia = wp.media.frames.file_frame = wp.media({
        title: 'Select Image',
        multiple: true,
        button:{
            text: 'Select Media'
        },
    });

    /**
     * [on description]
     *
     * @param   {[type]}  click          [click description]
     * @param   {[type]}  processUpload  [processUpload description]
     *
     * @return  {[type]}                 [return description]
     */
    uploadButton.on('click', openUploadMedia);

    /**
     * [on description]
     *
     * @param   {[type]}  select       [select description]
     * @param   {[type]}  selectFiles  [selectFiles description]
     *
     * @return  {[type]}               [return description]
     */
    uploadMedia.on('select', selectFiles);

    /**
     * Upload processing
     *
     * @param   Object  Onclick event
     *
     * @return  void
     */
    function openUploadMedia(event) {
        event.preventDefault();
        uploadMedia.open();
    }

    /**
     * Select files from media library or upload new file
     *
     * @return  void
     */
    function selectFiles() {
        let attatchment = uploadMedia.state().get('selection').toJSON();
        
        attatchment.forEach(element => {
            let html = `<img src="${element.url}"/>`;
            imageContainer.append(html);
        });
    }

})(jQuery);

File Upload on WordPress

$image = isset( $_FILES['image'] ) ? $_FILES['image'] : '';


if ( $image ) {
    $upload = wp_handle_upload( $image, array( 'test_form' => false )  );
    $attachent_id = wp_insert_attachment( [
        'guid'           => $upload['url'],
        'post_mime_type' => $upload['type'],
        'post_title'     => basename( $upload['file'] ),
        'post_content'   => '',
        'post_status'    => 'inherit',
    ] );
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment