BLOG

How to use wp media uploader in a external non-wp page or in frontend

Hello!

I have a iframe shortcode generator inside of wordpress and I needed to get the wp uploader to insert media on it. Wheter you need it on a external page / frontend / whatever, this is the tutorial for you.

First we need to load WordPress in our file. If it’s the frontend you want to use the uploader on, you probably don’t need to load wp again. Anyway, I have a file get_wp.php that I just call on the file. This is my implementation of get_wp.php


then we get access to core functions like

require_once(dirname(__FILE__).'/get_wp.php');
$url_admin = get_admin_url();

add these right away

var ajaxurl = "";
var pagenow = 'dzs_portfolio',
typenow = 'dzs_portfolio',
adminpage = 'post-php',
thousandsSeparator = ',',
decimalPoint = '.',
isRtl = 0;
var wordCountL10n = {"type":"w"};
var thickboxL10n = {"next":"Next >","prev":"< Prev","image":"Image","of":"of","close":"Close","noiframes":"This feature requires inline frames. You have iframes disabled or your browser does not support them.","loadingAnimation":"/wp-includes/js/thickbox/loadingAnimation.gif","closeImage":"/wp-includes/js/thickbox/tb-close.png"};
var commonL10n = {"warnDelete":"You are about to permanently delete the selected items.n  'Cancel' to stop, 'OK' to delete."};
var wpAjax = {"noPerm":"You do not have permission to do that.","broken":"An unidentified error has occurred."};
var autosaveL10n = {"autosaveInterval":"60","savingText":"Saving Draftu2026","saveAlert":"The changes you made will be lost if you navigate away from this page.","blog_id":"1"};
var quicktagsL10n = {"closeAllOpenTags":"Close all open tags","closeTags":"close tags","enterURL":"Enter the URL","enterImageURL":"Enter the URL of the image","enterImageDescription":"Enter a description of the image","fullscreen":"fullscreen","toggleFullscreen":"Toggle fullscreen mode","textdirection":"text direction","toggleTextdirection":"Toggle Editor Text Direction"};var adminCommentsL10n = {"hotkeys_highlight_first":"","hotkeys_highlight_last":"","replyApprove":"Approve and Reply","reply":"Reply"};var heartbeatSettings = {"nonce":"ecc15b5e95"};var postL10n = {"ok":"OK","cancel":"Cancel","publishOn":"Publish on:","publishOnFuture":"Schedule for:","publishOnPast":"Published on:","dateFormat":"%1$s %2$s, %3$s @ %4$s : %5$s","showcomm":"Show more comments","endcomm":"No more comments found.","publish":"Publish","schedule":"Schedule","update":"Update","savePending":"Save as Pending","saveDraft":"Save Draft","private":"Private","public":"Public","publicSticky":"Public, Sticky","password":"Password Protected","privatelyPublished":"Privately Published","published":"Published","comma":","};var _wpUtilSettings = {"ajax":{"url":"admin-ajax.php"}};var _wpMediaModelsL10n = {"settings":{"ajaxurl":"admin-ajax.php","post":{"id":0}}};var pluploadL10n = {"queue_limit_exceeded":"You have attempted to queue too many files.","file_exceeds_size_limit":"%s exceeds the maximum upload size for this site.","zero_byte_file":"This file is empty. Please try another.","invalid_filetype":"This file type is not allowed. Please try another.","not_an_image":"This file is not an image. Please try another.","image_memory_exceeded":"Memory exceeded. Please try another smaller file.","image_dimensions_exceeded":"This is larger than the maximum size. Please try another.","default_error":"An error occurred in the upload. Please try again later.","missing_upload_url":"There was a configuration error. Please contact the server administrator.","upload_limit_exceeded":"You may only upload 1 file.","http_error":"HTTP error.","upload_failed":"Upload failed.","big_upload_failed":"Please try uploading this file with the %1$sbrowser uploader%2$s.","big_upload_queued":"%s exceeds the maximum upload size for the multi-file uploader when used in your browser.","io_error":"IO error.","security_error":"Security error.","file_cancelled":"File canceled.","upload_stopped":"Upload stopped.","dismiss":"Dismiss","crunching":"Crunchingu2026","deleted":"moved to the trash.","error_uploading":"u201c%su201d has failed to upload."};
var _wpPluploadSettings = {"defaults":{"runtimes":"html5,silverlight,flash,html4","file_data_name":"async-upload","multiple_queues":true,"max_file_size":"33554432b","url":"async-upload.php","flash_swf_url":"/wp-includes/js/plupload/plupload.flash.swf","silverlight_xap_url":"/wp-includes/js/plupload/plupload.silverlight.xap","filters":[{"title":"Allowed Files","extensions":"*"}],"multipart":true,"urlstream_upload":true,"multipart_params":{"action":"upload-attachment","_wpnonce":"773ef53e9b"}},"browser":{"mobile":false,"supported":true},"limitExceeded":false};
var _wpMediaViewsL10n = {"url":"URL","addMedia":"Add Media","search":"Search","select":"Select","cancel":"Cancel","selected":"%d selected","dragInfo":"Drag and drop to reorder images.","uploadFilesTitle":"Upload Files","uploadImagesTitle":"Upload Images","mediaLibraryTitle":"Media Library","insertMediaTitle":"Insert Media","createNewGallery":"Create a new gallery","returnToLibrary":"u2190 Return to library","allMediaItems":"All media items","noItemsFound":"No items found.","insertIntoPost":"Insert into post","uploadedToThisPost":"Uploaded to this post","warnDelete":"You are about to permanently delete this item.n  'Cancel' to stop, 'OK' to delete.","insertFromUrlTitle":"Insert from URL","setFeaturedImageTitle":"Set Featured Image","setFeaturedImage":"Set featured image","createGalleryTitle":"Create Gallery","editGalleryTitle":"Edit Gallery","cancelGalleryTitle":"u2190 Cancel Gallery","insertGallery":"Insert gallery","updateGallery":"Update gallery","addToGallery":"Add to gallery","addToGalleryTitle":"Add to Gallery","reverseOrder":"Reverse order","settings":{"tabs":[],"tabUrl":"media-upload.php?chromeless=1","mimeTypes":{"image":"Images","audio":"Audio","video":"Video"},"captions":true,"nonce":{"sendToEditor":"0aef7a9d93"},"post":{"id":3905,"nonce":"0ba07d0c8c","featuredImageId":"3577"},"defaultProps":{"link":"","align":"","size":""},"embedExts":["mp3","ogg","wma","m4a","wav","mp4","m4v","webm","ogv","wmv","flv"]}};var authcheckL10n = {"beforeunload":"Your session has expired. You can log in again from this page or go to the login page.","interval":"180"};var wordCountL10n = {"type":"w"};var wpLinkL10n = {"title":"Insert/edit link","update":"Update","save":"Add Link","noTitle":"(no title)","noMatchesFound":"No matches found."};/* ]]> */

this in your <head> tag


        
        

then, this in your html






	

	

	

	

	

	

	

	

	

	

	

	

	
		
        
        

You should now have a functional wp media uploader that you can call with

// Uploading files - from http://mikejolley.com/2012/12/using-the-new-wordpress-3-5-media-uploader-in-plugins/
var file_frame;
 
  jQuery('.upload_image_button').live('click', function( event ){
 
    event.preventDefault();
 
    // If the media frame already exists, reopen it.
    if ( file_frame ) {
      file_frame.open();
      return;
    }
 
    // Create the media frame.
    file_frame = wp.media.frames.file_frame = wp.media({
      title: jQuery( this ).data( 'uploader_title' ),
      button: {
        text: jQuery( this ).data( 'uploader_button_text' ),
      },
      multiple: false  // Set to true to allow multiple files to be selected
    });
 
    // When an image is selected, run a callback.
    file_frame.on( 'select', function() {
      // We set multiple to false so only get one image from the uploader
      attachment = file_frame.state().get('selection').first().toJSON();
 
      // Do something with attachment.id and/or attachment.url here
    });
 
    // Finally, open the modal
    file_frame.open();
  });

  • probonobusiness
    March 19, 2015 at 10:27 pm

    I¡¦ll right away grab your rss as I can not in finding your email subscription link or newsletter service. Do you have any? Please let me understand so that I may subscribe. Thanks.

  • icelandautorental
    June 3, 2015 at 6:54 am

    Thanks for such a nice post. I found a lot of useful tips from this post. Keep blogging.thanks for sharing. good bye.

  • redbellfood.
    June 3, 2015 at 6:54 pm

    All i want to tell is to thank you greatly for bringing up this complicated matter to open exchange of thoughts and conducting it so well. Great info calls for yet another visit to your website!

Leave a comment

Your email address will not be published

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

7 + 1 =

{"type":"main_options","images_arr":"'#ffffff'","enable_ajax":"off","soundcloud_apikey":"","bg_isparallax":"off","bg_slideshow_time":"0","bg_transition":"slidedown","site_url":"http:\/\/digitalzoomstudio.net","theme_url":"http:\/\/digitalzoomstudio.net\/wp-content\/themes\/qucreative\/","blur_ammount":"26","width_column":"50","width_section_bg":"","width_gap":"30","border_width":"0","border_color":"#ffffff","translate_leave_a_comment":"Leave a comment","translate_leave_a_comment_to":"Leave a comment to","is_customize_preview":"off","width_blur_margin":"30","gallery_w_thumbs_autoplay_videos":"off","enable_native_scrollbar":"on","content_enviroment_opacity":"30","menu_enviroment_opacity":"70"}
{"type":"darkfull"}