How to add the media uploader in wordpress plugin

  • 5 years-11 months

    How to add the media uploader in wordpress plugin

    • Category : php
    • Viewed : 89 times
    • Posted On :
    • Posted by : Vikas

    When i click the first upload field (uploading process are success) after insert into post that corresponding media url is appear in the second field not in first. I am not sure where is the problem any suggestion would be great.

    <?php
    wp_enqueue_script('jquery');
    // This will enqueue the Media Uploader script
    wp_enqueue_media();
    ?>
        <div>
        <label for="image_url">Image</label>
        <input type="text" name="image_url" id="image_url" class="regular-text">
        <input type="button" name="upload-btn" id="upload-btn" class="button-secondary" value="Upload Image">
     </div>
    <script type="text/javascript">
    
    jQuery(document).ready(function($){
        $('#upload-btn').click(function(e) {
            e.preventDefault();
            var image = wp.media({ 
                title: 'Upload Image',
                // mutiple: true if you want to upload multiple files at once
                multiple: false
            }).open()
            .on('select', function(e){
                // This will return the selected image from the Media Uploader, the result is an object
                var uploaded_image = image.state().get('selection').first();
                // We convert uploaded_image to a JSON object to make accessing it easier
                // Output to the console uploaded_image
                console.log(uploaded_image);
                var image_url = uploaded_image.toJSON().url;
                // Let's assign the url value to the input field
                $('#image_url').val(image_url);
            });
        });
    });
    </script>
    
    
    
    // UPLOAD ENGINE
    function load_wp_media_files() {
        wp_enqueue_media();
    }
    add_action( 'admin_enqueue_scripts', 'load_wp_media_files' );
     

Report this or Ask your own question

Your Answer

When answering a question please:
  1. Read the question carefully.
  2. Understand that English isn't everyone's first language so be lenient of bad spelling and grammar.
  3. If a question is poorly phrased then either ask for clarification, ignore it, or edit the question and fix the problem. Insults are not welcome.
Let's work to help developers, not make them feel stupid.