Replacing select2 in admin backend for all selects

The trouble is to do with how quick edit works – WordPress uses a hidden <div /> to generate the form, which will have already had select2 applied (and thusly, the positions already calculated).

Your click event listener on the body won’t fire when you need it, since the core event handler for quick edit returns false, stopping any event propagation. Instead, you can sneakily listen to the focus event for the title input, which is fired once the quick edit form is rendered:

jQuery( document ).ready(
    function( $ ) {
        $( "select:visible" ).select2(); // Only fire on visible inputs to begin with.
        $( document.body ).on( "focus", ".ptitle,select",
            function ( ev ) {
                if ( ev.target.nodeName === "SELECT" ) {
                    // Fire for this element only
                    $( this ).select2({ width: "element" });
                } else {
                    // Fire again, but only for selects that haven't yet been select2'd
                    $( "select:visible" ).not( ".select2-offscreen" ).select2({
                        width: "element"
                    });
                }
            }
        );
    }
);

You’ll see I’ve also added the width: "element" argument. This means select2 will calculate an appropriate width based on the length of the options. Without it, select2 is far too narrow for some of the options, particularly “Page Parent” with long page titles.

This solution will specifically solve your issue with quick edit, but you’ll probably need to implement additional “fixes” for other dynamic situations, particularly if you want to play nice with plugins like Advanced Custom Fields.

Leave a Comment