skip to Main Content

Adding A Search Form to WP_List_Table

The WP_List_Table class is very handy but it lacks a few features that many people want to include in their plugin pages: Search. This little snippet is based off the example plugin provided by WordPress. You will see many people in the forums ask why there is no example included with search and that’s becuase there is no one size fits all solution. I think I have a pretty good one that should help most people looking to add search to their table classes. This might not fit everyones needs, but if you used the WordPress example plugin as a basis for your table class it will drop right in.

Step One

The first step is to add the search form to the page your table is on. This is very simple. and WordPress will do most of the work for you. Wrap the generated form code in a form tag, add the page name in a hidden variable so that WordPress knows what page we are on, and your done.

Step Two

Step Two is where things get tricky. As usual you would call tabelclass->prepare_items() but we are going to hack this to allow for a search parameter. The first thing we want to do is check to see if a search term is set, then call our prepare with the search string.

Next, we can add a search variable to the prepare_items() method, and make a simple if statement to filter the data in the table by what the user searched for. First make sure you add the search term to the prepare_items() method: function prepare_items($search = NULL){

Then you can check if a search value is supplied, and return a mySQL search instead of the normal data set:

That’s all you really need to change for basic search. If you are having trouble adding a search box to WP_List_Table this should point you in the right direction. The best part is you can search all of your columns instead of just one, and you do not need to built out complete tables that become bulky and cumbersome. All you need is a few lines of code to add the form to your table pages.

Leave a Reply