Ultimate Guide to WordPress Post and Page Filtering

Last Updated on September 21, 2022 by 17 Comments

Ultimate Guide to WordPress Post and Page Filtering
Blog / Tips & Tricks / Ultimate Guide to WordPress Post and Page Filtering

If youโ€™ve ever shopped on Amazon, itโ€™s likely you already appreciate the power of filters to drill down into a large body of content and locate exactly what youโ€™re after. When searching for a product on Amazon there is always a sidebar full of filters that help you refine your search, returning just the results that meet your most important requirements. Filters like customer rating, brand, whether the product is for men or women, condition (new/used), and many more.

Given how useful content filters are, it should probably come as no surprise that the ability to create them for your WordPress content is built right into WordPress Core. And with a little know-how, you can bring that power to your site visitorsโ€“allowing them to navigate your content more nimbly than ever before.

In this post, we are going to walk you through the process of creating content filtering options for your users with a plugin.

Letโ€™s get started!

Why WordPress Post and Page Filtering?

WordPress is incredibly flexible. The core allows you to have complete control over everything on your site. Post and page filtering is one of the most powerful features of WordPress. There are several built-in functions for posts, pages, and custom content. Additionally, there are many ways to select, group, and filter items stored in the database. You can create sortable lists of search results by page template, post types, taxonomy terms, template hierarchy, product pages, or anything else you want.

By default, WordPress comes with a built in search function. However, that search function leaves a lot to be desired and doesnโ€™t help when your readers want to filter the results in a particular way. Thatโ€™s where the help of a third-party plugin comes into play.

What Does Search & Filter Plugin Do?

Search & Filter plugin is an easy to use plugin that takes the default WordPress search box to the next level. It allows your visitors to search for a particular term and filter the results based on categories, tags, custom post types, custom taxonomies, date range, or even a combination of all of them for a more refined search and more accurate results.

Using the plugin is dead simple. After you install and activate the plugin, youโ€™ll be taken to the settings page with a detailed explanation of how to use it. In a nutshell, you can use a shortcode anywhere in your posts, pages or any widgetized sidebars. Alternatively, if youโ€™re feeling brave and donโ€™t mind getting your hands dirty with a little code, you can paste a single line of code in your theme file.

Letโ€™s take a look at a few examples.

How to Filter Posts With Search & Filter

The most basic usage of the plugin is the shortcode that allows visitors to search through all your categories and tags. The default shortcode looks like this:

[searchandfilter fields="search,category,post_tag"] 

You can insert it into any post, page or a text widget and it will display the filtering options with search, category, and tags fields on the front end:

If you want to let visitors select more than one category or a tag, you can easily do so by modifying the shortcode to include checkboxes instead of a dropdown and labeling each field:

[searchandfilter headings="Select categories:" types="checkbox" fields="category"]

The examples above show how to use the plugin in the sidebar. However, you can also use it within your theme file to display it on any page. In the example below, the form displays on the blog page. All you have to do is paste the following line of code:

<?php echo do_shortcode('[searchandfilter fields="search,category,post_tag"]'); ?>

In our case, weโ€™ve added it to the main index template of Twenty Seventeen theme.

How to Filter Custom Taxonomies?

The above examples show a very basic usage of the plugin. But, Search & Filter plugin accepts other parameters as well. You can use a shortcode that allows your visitors to filter the search results only for custom taxonomies.

Letโ€™s say you have a shop on your site with WooCommerce. If you want to include product categories in the search results, all you have to do is add the following shortcode:

[searchandfilter taxonomies="search,category,post_tag,product_cat" headings=",Categories,Tags,Product Categories"]

In this example, Iโ€™ve also added headings before each field so visitors have an easier time distinguishing between fields:

If you wanted to display this on a page in your theme, then all you need to do is paste the following line of code in the appropriate page template under Appearance > Themes > Editor:

<?php echo do_shortcode('[searchandfilter taxonomies="search,category,post_tag,product_cat" headings=",Categories,Tags,Product Categories"]'); ?>

How to Filter Posts By Date Range?

Another case use is if you want to let your visitors search for posts in particular category within a certain date range. In that case, simply paste the following line of code in your archive.php:

<?php echo do_shortcode('[searchandfilter fields="search,post_date" types=",daterange" headings=",Post Date"]'); ?>

How to Filter Post Formats and Pages?

In the final example, letโ€™s take a look at filtering post formats and pages. If you publish video or audio posts, this shortcode will allow visitors only to find posts that belong to the post format you specify:

[searchandfilter fields="search,post_format" types=",select" headings=",Post Format" submit_label="Filter"]

If you want visitors to filter pages or posts, then all you need is shortcode that accepts post types as parameters:

[searchandfilter fields="search,post_types" post_types="post,page" headings=",Post Types"]

Aside from the examples above, the plugin letโ€™s you get even more specific by including parameters for ordering the results in hierarchical order, to show the count of posts in specified categories, add classes, filter authors, and much more.

How to Filter Posts Manually

As with anything WordPress related, there is a way to do it without the use of a plugin. Letโ€™s say you want to create a simple form that lets visitors filter posts from a certain category.
First, you need to create a simple form:

<form action="<?php echo site_url() ?>/wp-admin/admin-ajax.php" method="POST" id="filter">
    <?php
        if( $terms = get_terms( 'category', 'orderby=name' ) ) : 
            echo '<select name="categoryfilter"><option>Select category...</option>';
            foreach ( $terms as $term ) :
                echo '<option value="' . $term->term_id . '">' . $term->name . '</option>'; 
            endforeach;
            echo '</select>';
        endif;
    ?>
    <label>
        <input type="radio" name="date" value="ASC" /> Date: Ascending
    </label>
    <label>
        <input type="radio" name="date" value="DESC" selected="selected" /> Date: Descending
    </label>
    <button>Apply filters</button>
    <input type="hidden" name="action" value="customfilter">
</form>
<div id="response"></div>

In the form above, the first part simply lets the user select the taxonomies by using the get_terms function. You can use this for default categories and tags as well as custom taxonomies. The next part adds the radio buttons that allow visitors to display the results in ascending or descending order. Finally, the last part is the button for the form that allows them to apply the selected filters.

The entire form was added to sidebar.php template in Appearance > Themes > Editor.

The next step is to use the jQuery so results can be displayed without having to reload the page:

jQuery(function($){
    $('#filter').submit(function(){
        var filter = $('#filter');
        $.ajax({
            url:filter.attr('action'),
            data:filter.serialize(), // form data
            type:filter.attr('method'), // POST
            beforeSend:function(xhr){
                filter.find('button').text('Applying Filters...');          },
            success:function(data){
                filter.find('button').text('Apply filters');                $('#response').html(data); 
            }
        });
        return false;
    });
});

The last bit of code is to add a function to function.php file that will process the result based on the selected filters. It will look through the selected category and as long there are posts, it will display them by the date they were posted in ascending or descending order. If no posts are found in the category, it will show the message no posts were found:

 
function my_filters(){
    $args = array(
        'orderby' => 'date', 
        'order' => $_POST['date'] 
    );
 
        if( isset( $_POST['categoryfilter'] ) )
        $args['tax_query'] = array(
            array(
                'taxonomy' => 'category',
                'field' => 'id',
                'terms' => $_POST['categoryfilter']
            )
        );
  
    $query = new WP_Query( $args );
 
    if( $query->have_posts() ) :
        while( $query->have_posts() ): $query->the_post();
            echo '<h2>' . $query->post->post_title . '</h2>';
        endwhile;
        wp_reset_postdata();
    else :
        echo 'No posts found';
    endif;
 
    die();
}
 
 
add_action('wp_ajax_customfilter', 'my_filters'); 
add_action('wp_ajax_nopriv_customfilter', 'my_filters');

The final result displays like this one the front-end:

Why You Should Let Your Readers Filter Posts and Pages in WordPress

The above methods are a great way to let users filter your posts. But why would you want to do that?

WordPress already allows you to organize your posts with categories and tags, but it only allows users to view a single category or tag at a time. Moreover, if you use custom post types that use their own categories, those categories will not be visible along with those used for regular posts.

The Search & Filter plugin is especially useful not only when you have a lot of different categories and tags paired with yearโ€™s worth of content, it also comes in handy if youโ€™ve added custom post types like portfolio, gallery, testimonial, and more.

Another example is that your visitors can easily use this plugin to filter through your products and find what they are looking for.ย And if youโ€™re familiar with the code, doing it manually allows you to have even more control over the way the search results are displayed and which parameters are used.

Wrapping Up

Making sure your website is easy to use by allowing your visitors to quickly find the content you want is a great way to provide them with a pleasant user experience and to encourage them to come back.ย If your site is rich with content, consider implementing page and post filtering to make sure they get the content they want to see more of.

Weโ€™d love to hear any of your experience with WordPress search and filtering. Let us know in the comments below.

Article thumbnail image by graphicglobe /ย shutterstock.comย 

Divi

Want To Build Better WordPress Websites? Start Here! ๐Ÿ‘‡

Take the first step towards a better website.

Get Started
Divi
Premade Layouts

Check Out These Related Posts

Splice Video Editor: An Overview and Review

Splice Video Editor: An Overview and Review

Updated on March 10, 2023 in Tips & Tricks

Video is a valuable form of content for social media. Unfortunately, creating quality videos is usually a long process that involves moving mobile footage to a desktop app for editing. However, mobile editing is on the rise. Apps such as Splice Video Editor make it possible to efficiently create...

View Full Post
How to Use Font Awesome On Your WordPress Website

How to Use Font Awesome On Your WordPress Website

Updated on September 16, 2022 in Tips & Tricks

When given the choice between using a vector icon or a static image, it’s a good idea to go with the vector. They’re small and fast to load, and they can scale to any size without a loss of resolution. Font Awesome is a superb library of vector icons that you can use on your websites,...

View Full Post

17 Comments

  1. I have a question about integrating regular posts and custom-type posts. I thought I had an answer since I used the same category for either one. The filter works but there is no way to sort the two types of posts. The regular posts sort first; followed by a set of custom-type posts. Since I have posts that go back years, this isn’t working for me.

    thanks

  2. I’ve been looking for a search and filter program that allows users to pick two categories, with one of the filters = category1 and the other a list of categories. Will I be able to do this. I have a volunteer category and then list of areas where people could serve.

  3. The code doesn’t work for me. It loads the “/wp-admin/admin-ajax.php” page with a list of the articles.

    So it doesn’t stay on the same page.

  4. Other plugins for this that I know are SearchWP, FacetWP and Algolia. I didn’t like SearchWP, I tried later Algolia because it has a free version and I didn’t even have to try FacetWP (entirely premium). Algolia’s plugin is the bomb. So fast, so beautiful, so easy to configure… Love it.

  5. Super, I don’t often build very big websites, but I am just about to, and this will be a nice feature. Very helpful. Thank you.

  6. I have not tried this plugin, but I can say that a similar premium plugin, FavetWP, is *excellent*. And they have also have super helpful support.

  7. I’m building a website for a tile wholesale store. They want to display all the types of tiles they sell and have users filter the tiles they are looking for based on price, type and range. How would I go about it?

  8. Very useful, thanks.

    I venture to ask once again why ET does not include in divi builder and theme the option to display post Tags below โ€” or elsewhere โ€” the post title. If there is a good reason, I would like to know it. Thank you ๐Ÿ™‚

  9. It can be used for a real estate site?

  10. amazing article ๐Ÿ™‚

  11. Excellent!! Thanks.

  12. Hi,

    Excellent article.. Very useful information at different levels… I would think
    most sites could use something like this. Was this the only or best plugin that you
    recommend?

    • I very recently discovered FacetWP. It is, however, a premium plugin. Support has been great and there’s a ton of info in their docs for customizing how it works.

      A couple of potential issues I see with the plugin, Search & Filter, mentioned in this post is that it hasn’t been updated in 12 months and their support forum has a lot of unanswered questions.

      • Thanks Adam… I will check out FAcetWP too

  13. that’s very practical. thanks for sharing

  14. Awesome! This is going to be very useful. Well timed too. Thanks.

  15. no images load

Leave A Reply

Comments are reviewed and must adhere to our comments policy.

Get Started With Divi