WordPress. How to use media library for choosing image in extrafields or media box

I have spent 3 hours, so maybe someone needs the solution. So I answered the question on my own.

Related posts

Leave a Reply

1 comment

  1. <?php echo media_buttons(); ?>
    
    <input id="category_image" type="hidden" size="100" name="category_meta[category_image]" value="" />
    <div id="category_image_preview"></div>
    
    <script>
    (function( $ ) {
    
        window.send_to_editor = function ( imgHtml ) {
    
        $( '#category_image_preview' ).html( imgHtml )
            var imgUrl = $( 'img', imgHtml ).attr( 'src' );
            $( '#category_image' ).val( imgUrl );
    
            tb_remove();
        };
    
    })( jQuery );
    </script>
    

    The result