以下是一些代码,当单击添加媒体按钮或在设置特色图像时打开媒体模式时,这些代码会将焦点设置为搜索字段。将此代码添加到主题functions.php
或者一个插件来使用它。
注意:这是我的原始解决方案的更新版本。我认为这个更灵活、更可靠,因为它利用了WP Media API。
/**
* When a wp.media Modal is opened, set the focus to the media toolbar\'s search field.
*/
add_action( \'admin_footer-post-new.php\', \'wpse_media_library_search_focus\' );
add_action( \'admin_footer-post.php\', \'wpse_media_library_search_focus\' );
function wpse_media_library_search_focus() { ?>
<script type="text/javascript">
( function( $ ) {
$( document ).ready( function() {
// Ensure the wp.media object is set, otherwise we can\'t do anything.
if ( wp.media ) {
// Ensure that the Modal is ready. This approach resolves the
// need for timers which were used in a previous version of my answer
// due to the modal not being ready yet.
wp.media.view.Modal.prototype.on( "ready", function() {
// console.log( "media modal ready" );
// Execute this code when a Modal is opened.
// via https://gist.github.com/soderlind/370720db977f27c20360
wp.media.view.Modal.prototype.on( "open", function() {
// console.log( "media modal open" );
// Select the the .media-modal within the current backbone view,
// find the search input, and set the focus.
// http://stackoverflow.com/a/8934067/3059883
$( ".media-modal", this.el ).find( "#media-search-input" ).focus();
});
// Execute this code when a Modal is closed.
wp.media.view.Modal.prototype.on( "close", function() {
// console.log( "media modal close" );
});
});
}
});
})( jQuery );
</script><?php
}
为了子孙后代,这是我发布的原始版本。我认为上面的版本要好得多。
add_action( \'admin_footer-post-new.php\', \'wpse_media_library_search_focus_old\' );
add_action( \'admin_footer-post.php\', \'wpse_media_library_search_focus_old\' );
function wpse_media_library_search_focus_old() {
?>
<script type="text/javascript">
(function($) {
$(document).ready( function() {
// Focus the search field for Posts
// http://wordpress-hackers.1065353.n5.nabble.com/JavaScript-events-on-media-popup-td42941.html
$(document.body).on( \'click\', \'.insert-media\', function( event ) {
wp.media.controller.Library.prototype.defaults.contentUserSetting = false;
setTimeout(function(){
$("[id^=__wp-uploader-id]").each( function( index ) {
if ( $(this).css(\'display\') != \'none\' ) {
$(this).find("#media-search-input").focus();
}
});
}, 20);
});
// Focus the search field for Post Thumbnails
$( \'#set-post-thumbnail\').on( \'click\', function( event ) {
wp.media.controller.FeaturedImage.prototype.defaults.contentUserSetting = true;
setTimeout(function(){
$("[id^=__wp-uploader-id]").each( function( index ) {
//alert( index + ": " + value );
if ( $(this).css(\'display\') != \'none\' ) {
$(this).find("#media-search-input").focus();
}
});
}, 20);
});
});
})(jQuery);
</script><?php
}