Filter news’ posts by its category checkboxes checked on a sidebar under WordPress

enter image description here

So here, I have the above screenshot which lists all the categories in my WordPress environment. I listed.

Read More

1)Parent category

  • Animals

Children categories of Animals

  • Bears
  • Gibbons
  • Orangutan
  • Rhinos
  • Tigers

2)Parent Category

Children categories of Campaigns

  • Asian Rhino Project
  • Australian Orangutan Project
  • Free the Bears
  • Silvery Gibbon Project

In my php file, I have the following code that makes up the display structure of my checkboxes.

<form action="<?php the_permalink(); ?>" id="filterForm" method="post">
<?php    

$parent_categories = get_categories($parent_args);

foreach($parent_categories as $parent_category){


//create main headings for other categories other than Uncategorized.
if($parent_category->name!="Uncategorized"){
    $category_label = "Filter By ";
    echo '<h3 style="font-size: 20px; color: rgb(255, 255, 255);text-shadow: 2px 3px 0px rgb(0, 0, 0);">'.$category_label.''.$parent_category->name.'</h3>';

    //fetch the parent category's id
    $firstchild_args['parent'] = $parent_category->term_id;
    $firstchild_categories = get_categories($firstchild_args);

    //fetch all the first level children categories
    foreach($firstchild_categories as $firstchild_category){
        $output = "";
        $output = $output."<label class="checkbox">";
        $output = $output."    <input type="checkbox"  value=".$firstchild_category->cat_ID." onclick="processForm()"><span style='font-size: 17px; color: rgb(255, 255, 255);text-shadow: 2px 3px 0px rgb(0, 0, 0);'>".$firstchild_category->name;
        $output = $output."</label>";

        echo $output;
    }

}

}

?>
<input type="hidden" name="submitted" id="submitted" value="true">
</form>

While this is fine for displaying my categories, but when trying to implement some server-side functions when user toggles multiple checkbox clicks, I’m struggling to figure out which are the correct hooks/filters I should use to do this effectively.

Filter posts by multiple checkbox categories – wordpress

But after reading and experimenting for a while, I found his approach is not quite I was looking for. My thinking is that when a user checks one of the category checkboxes, the onclick event will trigger the form submission and WordPress will begin to process $_POST arguments right away then I will use WP_Query object to retrieved the passed-in arguments to process so that my lists of news posts will get filtered by its category checked checkboxes accordinly…

But I couldn’t achieve what I needed after following the above link!

What should I do next?

Related posts

Leave a Reply