Skip to content

Instantly share code, notes, and snippets.

@vralle
Last active September 22, 2022 19:57
Show Gist options
  • Save vralle/9e28e9d18a4b340b93ad to your computer and use it in GitHub Desktop.
Save vralle/9e28e9d18a4b340b93ad to your computer and use it in GitHub Desktop.
Adding a Media Button to the WordPress Editor.
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;
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;
}
});
<?php
// Add Btn after 'Media'
add_action( 'media_buttons', 'add_my_media_button', 15);
function add_my_media_button() {
echo '<a href="#" id="insert-my-media" class="button">Add my media</a>';
}
// Add js to admin
add_action( 'wp_enqueue_media', 'include_media_button_js_file' );
function include_media_button_js_file() {
wp_enqueue_script( 'media_button', plugin_dir_url( __FILE__ ) . 'assets/admin.js', array('jquery'), '1.0', true );
}
// Inserts new tab to wp.media
add_filter( 'media_upload_tabs', 'my_media_menu' );
function my_media_menu( $tabs ) {
$newtab = array( 'my_custom_tab' => __('My Tab') );
return array_merge($tabs, $newtab);
}
@oxhey
Copy link

oxhey commented Feb 18, 2017

If I set multiple to true, how do I get the second id?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment