(function($) {
$(document).ready( function() {
var file_frame;
$( '#button-id' ).on( 'click', function( event ) {
event.preventDefault();
if ( file_frame ) {
file_frame.open();
return;
}
file_frame = wp.media.frames.file_frame = wp.media({
title: $( this ).data( 'uploader_title' ),
button: {
text: $( this ).data( 'uploader_button_text' ),
},
multiple: false // set this to true for multiple file selection
});
file_frame.on( 'select', function() {
attachment = file_frame.state().get('selection').first().toJSON();
// do something with attachment here
});
file_frame.open();
});
});
})(jQuery);
<?php
class Some_WP_Plugin {
/**
* Init everything here
*/
public function __construct() {
add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_scripts' ) );
add_filter( 'ajax_query_attachments_args', array( $this, 'filter_media' ) );
}
/**
* Call wp_enqueue_media() to load up all the scripts we need for media uploader
*/
public function enqueue_scripts() {
wp_enqueue_media();
wp_enqueue_script(
'some-script',
plugins_url( '/', __FILE__ ) . 'js/some_script.js',
array( 'jquery' ),
'2014-01-27'
);
}
/**
* This filter insures users only see their own media
*/
public function filter_media( $query ) {
// admins get to see everything
if ( ! current_user_can( 'manage_options' ) )
$query['author'] = get_current_user_id();
return $query;
}
}
new Some_WP_Plugin();