In WordPress Dashboard there are some default columns listed for any of your post types on the post listing page. We can sort our custom posts by Ascending or Descending order by just clicking these fields. However most of the times these fields are not enough.

E.g. if we create a custom post for books then we may need columns to sort or filter books by Year of publication, Author, Category, etc

So how do we create these extra columns for sorting and filtering

Assumptions

  1. Custom Post Type: book
  2. Year,  Author and Language information is stored in custom meta fields for each book

Se here are the steps

Step 1: Define the custom colums

Here we add two new columns to the admin panel of the custom post type book namely Publication Year and Author

Step 2: Fill Data to the columns

Here we are assigning data to the columns displayed in the custom post. Since the data is stored in the post meta we use get_post_meta function to get the data from the postmeta table.

Step 3: Define sortable colums

Here we are defining which columns are sortable. In our case we want all the columns to be sortable.

Step 4: Perform Sorting

Here we are using the request filterThis filter is applied to the query variables that are passed to the default main SQL query of the page. This filter adds additional parameters/filters to the query variable based on which the list of posts gets generated.

Until this step the additional columns are added to the custom post type listing page and they are sortable. They can be sorted by clicking the table heading as shown below

Additional columns

 

Step 5: Create Filters

This part of code can vary depending upon our configuration of custom fields and taxonomy. Main objective here is to create select boxes for the filters. Below approach shows how to create select boxes for data stored in custom meta fields. If the data is stored is categories then we may need to use wp_dropdown_categories function to list categories for the filter

Step 7: Perform Filtering

Here we are just altering the main query for the page by passing our own variables.

This will create filters as shown below

Custom Filter admin screen

Leave a Reply

Your email address will not be published. Required fields are marked *