Skip to content

Instantly share code, notes, and snippets.

@ducwp
Forked from igorbenic/admin.js
Created May 8, 2021 07:18
Show Gist options
  • Save ducwp/0b8bb880de541d3bfce946bcef2df106 to your computer and use it in GitHub Desktop.
Save ducwp/0b8bb880de541d3bfce946bcef2df106 to your computer and use it in GitHub Desktop.
Extending the WordPress Media Uploader: Custom Tab | http://ibenic.com/extending-wordpress-media-uploader-custom-tab
var Library = wp.media.controller.Library;
var oldMediaFrame = wp.media.view.MediaFrame.Post;
// Extending the current media library frame to add a new tab
wp.media.view.MediaFrame.Post = oldMediaFrame.extend({
initialize: function() {
// Calling the initalize method from the current frame before adding new functionality
oldMediaFrame.prototype.initialize.apply( this, arguments );
var options = this.options;
// Adding new tab
this.states.add([
new Library({
id: 'inserts',
title: 'Lucky 5',
priority: 20,
toolbar: 'main-insert',
filterable: 'all',
library: wp.media.query( options.library ),
multiple: false,
editable: false,
library: wp.media.query( _.defaults({
// Adding a new query parameter
lucky: 'lucky',
}, options.library ) ),
// Show the attachment display settings.
displaySettings: true,
// Update user settings when users adjust the
// attachment display settings.
displayUserSettings: true
}),
]);
},
});
<?php
add_action( 'admin_enqueue_scripts', 'ibenic_add_tab_script' );
/**
* Load the JavaScript on admin
*/
function ibenic_add_tab_script() {
// Adding the file with the plugin_dir_url. The file admin.js is in root of our plugin folder
// Change the URL for your project
wp_enqueue_script( 'admin-js', plugin_dir_url( __FILE__ ) . '/admin.js', array( 'jquery' ), '', true );
}
<?php
add_filter( 'ajax_query_attachments_args', 'ibenic_query_attachments', 99);
/**
* Change the query used to retrieve attachments
* The Query will retrieve 5 random attachments
*/
function ibenic_query_attachments( $args ) {
if( isset( $_POST['query']['lucky'] ) ) {
$args['orderby'] = 'rand';
$args['posts_per_page'] = '5';
unset( $_POST['query']['lucky'] );
}
return $args;
}
<?php
add_filter( 'ajax_query_attachments_args', 'ibenic_query_attachments', 99);
/**
* Change the query used to retrieve attachments
* The Query will retrieve 5 random attachments
*/
function ibenic_query_attachments( $args ) {
if( isset( $_POST['query']['lucky'] ) ) {
$args['post_mime_type'] = array( 'image/jpeg', 'image/png', 'image/gif' );
unset( $_POST['query']['lucky'] );
}
return $args;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment