Using jquery to filter WordPress posts by categories

I’m trying to display a news feed that can be filtered.

Lets say that the wordpress category “NEWS” has sub-categories of “Sports” “Business” and “Region1”, “Region2”, “Region3”..etc

Read More

So the page will look like this:

          ** ALL NEWS | Sports | Business  **

Region1

Region2

Region3

Here’s my post within the WordPress Loop:

                   //Get all posts with a category of "NEWS"
                    query_posts('cat=1' );
                while (have_posts()) : the_post();
                echo '<li class="';

                        //Display the categories
                        $categories = get_the_category();
                        $output = '';

                        if($categories){
                            foreach((get_the_category()) as $category) { 
                            $output = $category->cat_name .'-';
                            echo $output;
                            } 
                    }

This displays:

<li class="news-sports-region1">Article1</li>
<li class="news-business-region2">Article2</li>
<li class="news-sports-region3-">Article3</li> 

So in my jquery scripts i’m trying to figure out the best way to handle when the user clicks each category. Please let me know if you have a simpler solution than what I’m trying to do.

I need the code for:

If a user clicks on “Sports”, hide all posts that do not have the word “sports” in the CLASS.
I also need to know how to remember what region was clicked and to filter by that region selected.

My code’s a mess right now with a bunch of different solutions that I just can’t get to work.
I was trying to filter by applying the categories as “data-category” attributes, but hit a roadblock somewhere.

Please help, thanks!

Related posts

Leave a Reply

1 comment

  1. Firstly, it’ll help if you don’t connect the different classes together (ie, just put a space between “news sports region”). That way, you can apply a class to one particular class (“news”, or “sports”), instead of having to do something complicated to select part of the class (like div[class*=’news-‘]). If you get that done, then it will look like this:

    <li class="news sports region1">Article1</li>
    <li class="news business region2">Article2</li>
    <li class="news sports region3-">Article3</li> 
    

    Then all you need your jquery to do is animate the display/hide of those categories. Something like:

    $('.news').hide(600)
    $('.sports').show(600)
    

    I’m not super good at JQuery myself, so this is just kind of an overview of how to do it. Hopefully it gets you started.