wordpressmedia-library

Wordpress select image from Media Library


I create one theme for wordpress and on admin panel, I need to select image (Logo) from media library by admin site. I use this code but not work:

<?php
add_action ('admin_enqueue_scripts', function() {
    if(is_admin())
    wp_enqueue_media(); 
});
?>
<form method="post">
    <input type="text" class="process_custom_images" id="process_custom_images" name="selected_logo" value="" placeholder="http://">
    <button class="set_custom_logo button" style="vertical-align: middle;">Select Logo</button>
</form>

<script>
//“Add Media” button
jQuery(document).ready(function() {
    var $ = jQuery;
    if ($('.set_custom_logo').length > 0) {
        if ( typeof wp !== 'undefined' && wp.media && wp.media.editor) {
            $(document).on('click', '.set_custom_logo', function(e) {
                e.preventDefault();
                var button = $(this);
                var id = button.prev();
                wp.media.editor.send.attachment = function(props, attachment) {
                    id.val(attachment.url);
                };
                wp.media.editor.open(button);
                return false;
            });
        }
    }
});
</script>

But when I insert below code inside form tag, above code working well.

<div><?php wp_editor("", 'postcontent', $settings = array('textarea_rows'=> '10')); ?></div>

But I don't need text editor! Please help me. Thank's


Solution

  • First of all wp_enqueue_media(); should be in your functions.php file and should look something like this:

    function misha_include_script() {
        if ( ! did_action( 'wp_enqueue_media' ) ) {
            wp_enqueue_media();
        }
    }
    
    add_action( 'admin_enqueue_scripts', 'misha_include_script' );
    

    Second, the jQuery call in admin area is optimal to begin this way:

    jQuery(function( $ ){
    
        // your jQuery is here
    
    });
    

    I recommend to try the above tips, if it doesn't help, I hope this tutorial will be useful for you https://rudrastyh.com/wordpress/customizable-media-uploader.html