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 

The post Ultimate Guide to WordPress Post and Page Filtering appeared first on Elegant Themes Blog.



Source link

error: Content is protected !!