Adding a Media Button to the WordPress Content Editor

functions.php



function add_my_media_button() {
    echo '<a href="#" id="insert-my-media" class="button">Add my media</a>';
}
add_action('media_buttons', 'add_my_media_button');

function include_media_button_js_file() {
    wp_enqueue_script('media_button', 'path/to/media_button.js', array('jquery'), '1.0', true);
}
add_action('wp_enqueue_media', 'include_media_button_js_file');


media_button.js


jQuery(function($) {
    $(document).ready(function(){
            $('#insert-my-media').click(open_media_window);
        });

    function open_media_window() {
    if (this.window === undefined) {
        this.window = wp.media({
                title: 'Insert a media',
                library: {type: 'image'},
                multiple: false,
                button: {text: 'Insert'}
            });

        var self = this; // Needed to retrieve our variable in the anonymous function below
        this.window.on('select', function() {
                var first = self.window.state().get('selection').first().toJSON();
                wp.media.editor.insert('[myshortcode id="' + first.id + '"]');
            });
    }

    this.window.open();
    return false;
}
});