3

I was just wondering if it's possible somehow (via an addon maybe?) to set the initial focus when the WordPress media library pops up to be the search field?

I have a lot of posts where I need to select images very fast and need to type in the names of the images to find them and this would be exceptionally handy except I've looked on Wordpress.org and a few other places that I know of and can't find a plugin that can do this although someone here might know of one or perhaps a way of doing this?

Many thanks in advance,

Best wishes,

Mark

  • Are you referring to the actual Media Library page or the popup that shows when you are creating a new post and attempting to add an image or media file? – sMyles May 3 '17 at 22:00
  • Hi. Thank you so much for the utterly speedy reply, much appreciated! Unfortunately I'm not too sure what you are referring to when you say "…the popup that shows when you are creating a new post…"? I'm referring to the media library that pops up on the page whenever you click on Add Media or click on any custom fields that might bring up the media library window. Hope that helps a bit? The window which says Set Image and has the Upload Files and Media Library section headings in it and at the top has an input field that says Search media items…. Hope that helps? Thanks. – Mark Bowen May 3 '17 at 22:05
  • Ah sorry I think I know what you mean now!! Light bulb moment!! :-) Not the Media Library page no but the popup that appears in posts and pages when adding / changing an image / file etc… Cheers! – Mark Bowen May 3 '17 at 22:08
2

Here's some code that will set the focus to the search field when clicking on the Add Media button or when opening the media modal when setting a featured image. Add this code to your theme's functions.php or to a plugin to use it.

Note: This is an updated version of my original solution. I think this one is a little more flexible and reliable because it leverages the 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
}

For posterity's sake, here is the original version that I posted. I think the version above is much better.

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
}
  • 1
    Crikey!!! Without swearing, how in the blazes did you write that code that fast?!!! That's absolutely fantastic and after a very very quick test does exactly what I was after! An absolute trillion thank you's!! Best answer I've ever received to anything ever without a doubt! Where would I have to go to learn to even know where to do that sort of thing? – Mark Bowen May 3 '17 at 22:15
  • 1
    Aha! Knew there'd be something :-( I'd like to be able to use this across the whole of whenever the Media Library pops up. Specifically I'm currently using Visual Composer on a site and in some of the elements there is an add image or choose image button which pops up what looks to be the same window but unfortunately the field doesn't get focus. There are quite a few places actually where this sort of window pops up so I was hoping that it might work for all of them? – Mark Bowen May 3 '17 at 22:18
  • 1
    Okay seems as though (so far), most of the Visual Composer buttons have the class of .gallery_widget_add_images. I'm sure I'll find one that doesn't though!! :-) So my next question would be is there a way in the code you provided to have a list of classes that this function would fire upon so in laymans (my) terms ;-) if the button has this class or this class or this class and so on and so forth then fire the function? Thanks again for all your help on this it will really save me hours of work I'm sure. – Mark Bowen May 3 '17 at 22:28
  • 1
    Hiya. Just quickly pasted that into my functions.php file and so far seems to be working beautifully! Works for both the main Add Media button and also the buttons from within Visual Composer too. Haven't tried them all but looks like it will do from the way you've coded it. I'm terrible with Javascript but know just enough code to kind of understand what you've done there. Again, thank you so so much for this it will really help me out a lot. Best wishes, Mark. – Mark Bowen May 4 '17 at 7:15
  • 1
    Absolutely fantastic thank you!! I'll check this out later on and then I'm going to make this into a plugin as I'm sure I'll need it on other sites too. Thank you so so much! – Mark Bowen May 4 '17 at 8:46
0

First Method

This requires two parts, one to set the default tab as media library through filter, and one to add custom JS to set focus when Add Media is clicked

1.) Set default tab as Media Library:

add_filter( 'media_upload_default_tab', 'smyles_set_default_media_tab' );

function smyles_set_default_media_tab( $tab ){
    return 'library';
}

2.) Add custom JS to set focus

add_action( 'admin_footer', 'smyles_set_default_media_focus' );

function smyles_set_default_media_focus() {
    // Only output in footer when required
    if ( did_action( 'wp_enqueue_media' ) ):
    ?>
        <script type="text/javascript">
          jQuery( document ).ready( function ( $ ) {

              $( document ).on( 'click', '.insert-media', function(){
                    // Add slight delay before setting focus just in case
                    setTimeout( function(){
                        $( '#media-search-input' ).focus();
                    }, 50 );
              });

          } );
        </script>
    <?php
    endif;
}

Second Method

The second method only requires one step, which adds JS that will automatically find the Media Library tab when Add Media is clicked, and click that tab, which will also automatically set focus on the search field.

add_action( 'admin_footer', 'smyles_set_default_media_focus_v2' );

function smyles_set_default_media_focus_v2() {

    // Only execute when required
    if ( did_action( 'wp_enqueue_media' ) ):
        $tabs = media_upload_tabs();
        if( ! array_key_exists( 'library', $tabs ) ){
            return;
        }
    ?>
        <script type="text/javascript">
          jQuery( document ).ready( function ( $ ) {

              $( document ).on( 'click', '.insert-media', function(){
                    // Add slight delay for the modal to open
                    setTimeout( function(){
                        $( "a:contains('<?php echo $tabs['library']; ?>')" ).click();
                    }, 50 );
              });

          } );
        </script>
    <?php
    endif;
}

Voila! Profit!

  • Hi sMyles, Thank you for the code too. I've not tried it out as the code that Dave provided does seem to be doing everything I need it to do however I did notice that your code only fires when the normal Add Media button is clicked which is great but I did unfortunately also need it to fire when Visual Composer components are at play too. Thank you so much for providing an answer too though as it is very much appreciated. – Mark Bowen May 4 '17 at 7:17
  • No worries, glad you got it figured out :) – sMyles May 4 '17 at 13:10
0

With all thanks going to Dave Romsey for his above code I've now placed this into a quick plugin for WordPress incase anyone else ever needs anything like this.

Thanks again Dave!

Download / Clone plugin https://github.com/MarkBowenPiano/media-library-search-focus

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.