Uncategorized WordPress custom media upload for frontend
As you know about WordPress has a great functionality that is to upload a file and manage files and image using WordPress media box image manager .
you have been using this media box in post or page and custom post type in admin section as featured image.
As i have been trying many more time on internet to find out the correct solution but i did not find correct solution that i want . finally i discovered the right code that can be use on front or wherever you want to use this code. This is really simple and short code that can easily implemented as per your requirement.
First In functions.php , you have to add or load some JavaScript and CSS that is very important to open media box.
So Now copy this code in functions.php file in your theme.
/* Load Js and Css that support media box wordpress 3.5 or above */ function load_scripts_on_frontend() { wp_enqueue_media(); wp_enqueue_script('media-upload'); wp_enqueue_script('thickbox'); wp_enqueue_style('thickbox'); } add_action('admin_print_scripts', 'load_scripts_on_frontend'); add_action('admin_print_styles', 'load_scripts_on_frontend'); add_action('wp_enqueue_scripts', 'load_scripts_on_frontend'); add_action('wp_enqueue_styles', 'load_scripts_on_frontend');
Now you load the JS and Css , its time to initialize wp media library in jQuery.
<script> // WordPress custom media upload box script jQuery(document).ready(function($){ $('#uploadMe').on('click',function() { var send_attachment_to_back = wp.media.editor.send.attachment; /* prepare instance */ var buttonInstance = $(this); /* Now callback to image selection */ wp.media.editor.send.attachment = function(props, attachment) { $('#filer').val(attachment.url); wp.media.editor.send.attachment = send_attachment_to_back; } wp.media.editor.open(buttonInstance); return false; }); }); </script>
Now Its HTML where you can test this code. i used this code in custom template , you can use this code any where as you want .
You can add this this template and create a page in admin and select example template and update , now view this page.
<?php /** Template Name: Example Page */ ?> <?php get_header(); ?> <input type="type" name="filer" id="filer" > <button name="uploadMe" id="uploadMe"> Browse Me</button> <?php get_sidebar(); ?> <?php get_footer(); ?>
Now your media code is ready .
Happy Coding !