Skip to content

Instantly share code, notes, and snippets.

@dbspringer
Created January 28, 2014 01:56
Show Gist options
  • Save dbspringer/8661122 to your computer and use it in GitHub Desktop.
Save dbspringer/8661122 to your computer and use it in GitHub Desktop.
WordPress front-end uploader & current-user only media filter
<?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();
(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);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment