Use WordPress Media Uploader for Php Website

Handling media is one of the main issue faced by developers. This post explains how to use wordpress media uploader for external php websites. Mainly the upload functionality of WordPress will help us to handling uploading files our cms. Even we can add wp content editor with media uploader to our cms i will explain that in another post.

We need to install wordpress inside our custom cms folder so that it is easy to handle. Follow the steps carefully to use wp uploader to our php website

  • Consider upload.php is our file in which we need to integrate WordPress uploader.
  • include wordpress wp-blog-header.php on the top of the file. Eg: If the wordpress is installed in wp folder inside our cms we can add it like this :-
     require_once './wp/wp-blog-header.php';
  • Go to wp-includes functions.php and add the following to the top of the status_header function:
  • If it won’t work after all steps have done use the alternative
     $wp->init(); $wp->parse_request(); $wp->query_posts();
     $wp->register_globals(); $wp->send_headers();
  • We need to modify some wordpress functions  and add one function control wordpress cookies to stop mangling our cookies. Else we are not able to login to our cms.
  • Go to wp-includes folder and open load.php search for ‘wp_magic_quotes’ .
  • Put the following function just above the wp_magic_quotes function
     function cp_ignore_magic_quotes($value, $key) {
     if ($key != "session_name_here") {

    replace ‘session_name_here’ with your session name.

  • Modify  wp_magic_quote function by adding below code snippet.
    array_walk($_COOKIE, 'cp_ignore_magic_quotes');
     //$_COOKIE = add_magic_quotes( $_COOKIE );
  • Additionally add  our session name in $no_unset array.  It will be in top of the file.
    $no_unset = array( 'GLOBALS', '_GET', '_POST', '_COOKIE', '_REQUEST', \\
     '_SERVER', '_ENV', '_FILES', 'table_prefix','our_session' );
  • Next is adding scripts and css files for the media uploader.
  • Next we go back to the upload.php. Put below code to the top of the file
     require_once(path_to wp_folder/wp-includes/functions.php" );
     require_once(path_to wp_folder/wp-includes/media-template.php" );

    replace ‘path_to wp_folder’ with correct path.

  • Put the below code to the top of the file
     <link media="all" type="text/css" href="path_to_wp/wp-admin/load-styles.php?c=0&dir=ltr&load=wp-admin,buttons,media-views,dashicons&ver=3.8" rel="stylesheet" />
     <link id="colors-css" media="all" type="text/css" href="path_to_wp/wp-admin/css/colors.min.css?ver=3.8" rel="stylesheet" />
     <script type="text/javascript">
     jQuery(document).ready(function($) {
     var _custom_media = true,
     _orig_send_attachment =;$('.uploader .button').click(function(e) {
     var send_attachment_bkp =;
     var button = $(this);
     var id = button.attr('id').replace('_button', '');
     _custom_media = true; = function(props, attachment) {
     if (_custom_media) {
     $("#" + id).val(attachment.url);
     } else {
     return _orig_send_attachment.apply(this, [props, attachment]);
     return false;
    $('.add_media').on('click', function() {
     _custom_media = false;
     <script type='text/javascript' src='path_to_wp/wp-admin/load-scripts.php?c=1&load%5B%5D=utils,plupload, plupload-html5,plupload-flash,plupload-silverlight, plupload-html4,json2&ver=3.6.1'></script>
     <script type="text/javascript">
     addLoadEvent = function(func) {
     if (typeof jQuery != "undefined")
     else if (typeof wpOnload != 'function') {
     wpOnload = func;
     } else {
     var oldonload = wpOnload;
     wpOnload = function() {
     var ajaxurl = 'path_to_wp_folder/wp-admin/admin-ajax.php',
     pagenow = 'media',
     typenow = '',
     adminpage = 'media-new-php',
     thousandsSeparator = ',',
     decimalPoint = '.',
     isRtl = 0;
  •  <?php wp_print_media_templates(); ?>

    Use this function to echo media uploder templates in the bottom portion.

  • After that use following style and  script and modify according to your path of files.
     <link media="all" type="text/css" href="path_to_wp/wp-admin/wp-admin/load-styles.php?c=0&dir=ltr&load=wp-jquery-ui-dialog&ver=3.8" rel="stylesheet" />
     <script type="text/javascript">
     /* <![CDATA[ */
     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 Draft\u2026", "saveAlert": "The changes you made will be lost if you navigate away from this page.", "blog_id": "1"};
     var heartbeatSettings = {"nonce": "<?php echo wp_create_nonce( 'heartbeat-nonce' ); ?>", "suspension": "disable"};
     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 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": "path_to_wp\/wp-includes\/js\/thickbox\/loadingAnimation.gif"};
     var _wpUtilSettings = {"ajax": {"url": "path_to_wp\/wp-admin\/admin-ajax.php"}};
     var _wpMediaModelsL10n = {"settings": {"ajaxurl": "path_to_wp\/wp-admin\/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": "Crunching\u2026", "deleted": "moved to the trash.", "error_uploading": "\u201c%s\u201d has failed to upload."};
     var _wpPluploadSettings = {"defaults": {"runtimes": "html5,silverlight,flash,html4", "file_data_name": "async-upload", "multiple_queues": true, "max_file_size": "629145600b", "url": "path_to_wp\/wp-admin\/async-upload.php", "flash_swf_url": "path_to_wp\/wp-includes\/js\/plupload\/plupload.flash.swf", "silverlight_xap_url": "path_to_wp\/wp-includes\/js\/plupload\/plupload.silverlight.xap", "filters": [{"title": "Allowed Files", "extensions": "*"}], "multipart": true, "urlstream_upload": true, "multipart_params": {"post_id":0,"action":"upload-attachment","_wpnonce": "<?php echo wp_create_nonce('media-form'); ?>"}}, "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 page", "uploadedToThisPost": "Uploaded to this page", "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": "path_to_wp\/wp-admin\/media-upload.php?chromeless=1", "mimeTypes": {"image": "Images", "audio": "Audio", "video": "Video"}, "captions": true, "nonce": {"sendToEditor": "<?php echo wp_create_nonce('add-post'); ?>"}, "post": {"id": 0, "nonce": "<?php echo wp_create_nonce('add-post'); ?>", "featuredImageId": -1}, "defaultProps": {"link": "file", "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 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 wpLinkL10n = {"title": "Insert\/edit link", "update": "Update", "save": "Add Link", "noTitle": "(no title)", "noMatchesFound": "No matches found."};/* ]]> */
     </script><script src="path_to_wp/wp-admin/load-scripts.php?c=0&load%5B%5D=hoverIntent,common,suggest,jquery-color,wp-lists,jquery-ui-core,jquery-ui-widget,jq&load%5B%5D=uery-ui-mouse,jquery-ui-sortable,postbox,heartbeat,post,thickbox,underscore,shortcode,backbone,wp-util,wp-backbone,media-models,&load%5B%5D=wp-plupload,media-views,media-editor,svg-painter,wp-auth-check,jquery-ui-tabs,jquery-ui-draggable,jquery-ui-slider,jquery-touch-&load%5B%5D=punch,iris,wp-color-picker,media-upload,jquery-ui-button,jquery-ui-position,jque&load%5B%5D=ry-ui-dialog,wpdialogs,wplink,wpdialogs-popup,&ver=3.8" type="text/javascript"></script>
  • <div class="uploader"><input type="text" class="regular-text" /><input class="button" /> </div>

    This must be the structure of upload button to use the media uploader.   the text box with regular-text class will show the url of the uploaded file.

  • After doing all these we may suffer from upload error in WordPress uploader . so wee need to modify one more functions for that purpose
  • Go to wp-includes and open pluggable.php and edit wp_verify_nonce function add change the
    'return false'

    in the end of that function to

    'return 1'

Happy Browsing feel free to ask doubts if you having any trouble in implementing this. 🙂