How to Make Sortable Tables

<table class=”sortable”>

Adding the “sortable” class to a <table> element provides support for sorting by column value. Clicking the column headers will sort the table rows by that column’s value. Tables must use <thead> and <th> tags for sortable functionality to work. The <th> tag defines a header cell in an HTML table. An HTML table has two kinds of cells:

  • Header cells – contains header information (created with the <th> element)
  • Standard cells – contains data (created with the <td> element)

You will need to build or edit the table with the heading codes in the  WordPress Admin Text/HTML View rather than the Visual view in order to add the class to the table element and add table heading elements.  For instance, to make the example table of the 2012 Gold Medal Divers below, the beginning of the HTML table code is:

<table class="sortable">
 <thead>
   <tr>
     <th>Athlete</th>
     <th>Age</th>
     <th>Country</th>
     <th>Gold Medals</th>
  </tr>
 </thead>
  <tbody>
  <tr>
   <td>David Boudia</td>
   <td>23</td>
   <td>United States</td>
   <td>1</td>
  </tr>
  </tbody>
</table>
(repeat the row within the tbody tag for each table row needed.)

 

Example sortable table–click on any of the header cells of this table to sort by that column:

Athlete Age Country Gold Medals
David Boudia 23 United States 1
Chen Ruolin 19 China 2
He Zi 21 China 1
Qin Kai 26 China 1
Wu Minxia 26 China 2
Ilya Zakharov 21 Russia 1
Cao Yuan 17 China 1
Luo Yutong 26 China 1
Wang Hao 19 China 1
Zhang Yanquan 18 China 1

How to Make Searchable and Sortable Tables

<table class=”searchable sortable”>

Adding the “searchable sortable” class to a table tag also adds a search box to the table header. As the user types in the search box, table rows that do not have values matching the search input will be hidden. The rest of the code would be similar to the sortable table. Tables must use <thead> and <th> tags for sortable and searchable functionality to work. The <th> tag defines a header cell in an HTML table. An HTML table has two kinds of cells:

  • Header cells – contains header information (created with the <th> element)
  • Standard cells – contains data (created with the <td> element)

For instance, to make the example table of the 2012 Gold Medal Swimmers below, the beginning of the HTML table code is:

<table class="searchable sortable">
 <thead>
   <tr>
     <th>Athlete</th>
     <th>Age</th>
     <th>Country</th>
     <th>Gold Medals</th>
  </tr>
 </thead>
 <tbody>
   <tr>
    <td>Michael Phelps</td>
    <td>27</td>
    <td>United States</td>
    <td>4</td>
   </tr>
  </tbody>
</table>
(repeat the row within the tbody tag for each table row needed.)

Example searchable and sortable table–enter “China” in the search box to search: