Filter and Hooks, Programming, WordPress

jQuery ajax filtering posts with checkboxes

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

  1.  I want to check “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

if(inputElement.checked && inputElement.value != ‘all’){
document.querySelector(‘.js-filter-checkbox[value=”all”]’).checked = false;

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

if(inputElement.checked && inputElement.value == ‘all’){
item.checked = false;

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

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

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

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

Finally, posts are filtered based on the selected categories.

Hits: 989


Automatically open external links in new tab

Do you want to open all the external links of your website in a new tab ? If you say ‘YES“, just copy the  following code and paste it in your function.php file.


The aforementioned script excludes, if teljavascript.void(0), hash(#), mailto and site_url() are in the href of the anchor tag.

Hits: 7

Filter and Hooks

Want to open pdf in a new tab?

To open all the pdf in a new tab set the target=”_blank” for all .pdf extension in anchor, place the script in the footer.

You can also place the script inside the DOM ready.


Hits: 5

Filter and Hooks

add active class to the current menu using jquery

Sometimes, it is easy and fast to use jQuery to highlight the current menu. And just for this case,

If the menu to be highlighted is inside the container with class for eg. ‘main-nav’, then it would be good to add ‘.main-nav’ on the selector.

Hits: 8