Filter and Hooks, Programming, WordPress

jQuery ajax filtering posts with checkboxes

I think most of us are familiar with filtering posts based on categories using ajax. But, if you still want to check out the way to code for filtering the posts continue reading this article.

Let’s say, I have lists of categories in the checkbox and I want to filter posts based on the selected categories. I have three conditions for the categories filter :

  1.  I want to check the “All” checkbox by default and display all the posts accordingly.
  2.  If I check/select the filter other than “All”, the “All” checkbox should be unchecked & the posts of checked categories should be displayed
  3. If I check “All” categories, other selected categories should be unchecked

I begin…

Firstly, list all active categories associated with the posts

Add jQuery that tricks the checkbox as per requirement…

In the above js code,
1. All the checkbox are selected using querySelectorAll

2. var count = document.querySelectorAll(‘.js-filter-checkbox:checked’).length, gives the number of checked categories.

3. If the checkbox is checked and among the checked categories there is no “All”, “All’ is unchecked

4. If one of the checked category is “All”,  all the other checked categories are unchecked

5. If none of the categories is checked, the “All’ category is checked
if(count == 0) document.querySelector(‘.js-filter-checkbox[value=”all”]’).checked = true;

On page load “All” categories are checked so that all the posts are displayed by default

Ajax code is added to filter the posts based on checked categories

The hook that handles our ajax request is added on function.php  :

Create a div with the class name ‘js-posts-list’ for holding and displaying the ajax responses.

Finally, posts are filtered based on the selected categories.

Hits: 3459

Standard

2 thoughts on “jQuery ajax filtering posts with checkboxes

Comments are closed.