Skip to content

Instantly share code, notes, and snippets.

@maheshwaghmare
Last active June 14, 2019 07:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maheshwaghmare/9a212fb89660209337986f05db413e7d to your computer and use it in GitHub Desktop.
Save maheshwaghmare/9a212fb89660209337986f05db413e7d to your computer and use it in GitHub Desktop.
Add search widget input box into the WordPress widgets page.
<div class="widgets-search">
<input type="search" id="widgets-search-input" class="regular-text" placeholder="<?php _e('Search widgets...'); ?>">
</div>
/* =Widget Search
-------------------------------------------------------------- */
#widgets-search-input {
margin: 0 0 .2em 0;
width: 100%;
font-size: 16px;
font-weight: 300;
line-height: 1.5;
border-width: 1px;
border-style: solid;
border-color: #ddd;
}
.show-widget {
display: block;
}
.hide-widget {
display: none;
}
/*
* Use feature detection to determine whether inputs should use
* the `keyup` or `input` event. Input is preferred but lacks support
* in legacy browsers. See changeset 34078, see also ticket #26600#comment:59
*/
if ( 'oninput' in document.createElement( 'input' ) ) {
inputEvent = 'input';
} else {
inputEvent = 'keyup';
}
$( '#widgets-search-input' ).on( inputEvent, function() {
var search_term = $('#widgets-search-input').val() || '',
parent = $('#widgets-left'),
widgets = parent.find('.widget'),
widget_titles = parent.find('.widget-title');
if( search_term.length ) {
// Hide all widgets. Because, Below we show those widgets
// which have search term in the widget title.
widgets.addClass('hide-widget').removeClass('show-widget');
// Search widget and ONLY show these widgets which "contain" the widget title.
var rex = new RegExp( search_term, 'i');
widget_titles.filter(function () {
var widget_name = $.trim( $(this).text() ) || '';
return rex.test( widget_name );
}).parents('.widget').removeClass('hide-widget').addClass('show-widget');
} else {
// Show all widgets.
widgets.removeClass('hide-widget').addClass('show-widget');
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment