skip to Main Content

How to Create a Custom WooCommerce Product Filter with AJAX


Table of Contents

  1. Why Avoid Plugins for Filtering
  2. Creating a Filter for WooCommerce Products
  3. Handling AJAX Requests in PHP
  4. Conclusion
  5. FAQ

Overview

Many websites require the ability to filter WordPress posts dynamically, enhancing user experience. While plugins are a popular solution, they often introduce unnecessary features and code that can clutter your site. In this guide, we’ll show you how to implement a custom WooCommerce product filter by categories using AJAX, avoiding plugin dependency.


Why Avoid Plugins for Filtering

Using plugins to filter WooCommerce products is convenient but comes with drawbacks:

  • Performance Impact: Plugins can slow your site due to added overhead. Therefore, avoiding them can enhance performance.
  • Compatibility Issues: Some plugins may conflict with WordPress updates or other site elements. Consequently, they can disrupt functionality.
  • Maintenance Overhead: Plugins require frequent updates, adding to your workload. Thus, minimizing their use simplifies site maintenance.

By implementing a custom filter, you retain full control and reduce potential risks..


Creating a Filter for WooCommerce Products

This section demonstrates how to create a filter for WooCommerce products using AJAX to dynamically update content without reloading the page.

Adding the Filter Widget Code

The following PHP code creates a widget for users to filter products by category:

<div class="widget-box" id="filterbar-one">
    <h3><?php echo __( 'Filter By Categories', 'drh' ) ?><span></span></h3>
    <div class="textwidget">
        <?php
        $taxonomy     = 'product_cat';
        $orderby      = 'name';  
        $show_count   = 0;      // 1 for yes, 0 for no
        $pad_counts   = 0;      // 1 for yes, 0 for no
        $hierarchical = 1;      // 1 for yes, 0 for no  
        $title        = '';  
        $empty        = 0;
        $args = array(
            'taxonomy'     => $taxonomy,
            'orderby'      => $orderby,
            'show_count'   => $show_count,
            'pad_counts'   => $pad_counts,
            'hierarchical' => $hierarchical,
            'title_li'     => $title,
            'hide_empty'   => $empty
        );
        $all_categories = get_categories( $args );
        echo "<ul>";
        
        foreach ($all_categories as $cat) {
            $category_id = $cat->term_id;
        ?>
        <li>
            <input type="checkbox" id="" name="chk_cat_ids[]" class="p_cat styled-checkbox" value="<?php echo $cat->term_id ;?>">                
            <label class="styled-checkbox-label" for="styled-checkbox-1"><span class="styled-checkbox-lbl"><?php echo $cat->name ;?></span></label>               
        </li>
        <?php 
        }
        echo "</ul>";
        ?>
    </div>
</div>

<div class="mid-right full-right">
    <div id="product_results"></div>
</div>

This code creates an interactive way for users to filter products by category.

JavaScript for AJAX Functionality

The following JavaScript code handles the AJAX request and dynamically updates the product results:

<script type="text/javascript">
jQuery(".p_cat").change(function() {
    product_results_filters(1);    
});

var setpage = 1;
var perpage = 12;
product_results_filters(setpage);

function product_results_filters(setpage) {
    jQuery("#product_results").fadeIn(400).html('<div class="product_results-loader"><img src="<?php echo get_template_directory_uri().'/images/ripple.gif'; ?>" align="absmiddle" alt="Loading..." ></div>');
    jQuery.ajax({
        url: '<?php echo site_url(); ?>/wp-admin/admin-ajax.php',
        type: "post",
        data: {
            action: 'product_results_filters_ajax',
            setpage: setpage,
            perpage: perpage,
            p_cat_ids: jQuery("input:checkbox.p_cat:checked").serialize()
        },
        success: function(data) {        
            jQuery("#product_results").html(data);        
        },
        error: function() {
            //alert("failure");
        }                
    });
}
</script>

This script creates a smooth and responsive experience for users filtering through products.


Handling AJAX Requests in PHP

Add the following PHP function to your theme’s functions.php file to process the AJAX request:

<?php 

function fun_product_results_filters_ajax() { 
    ob_clean();
    
    $p_cat_ids = "";
    $p_cat_ids = explode("&", $_REQUEST['p_cat_ids']);

    $p_cat_ids_arr = array();
    if($_REQUEST['p_cat_ids'] != ""){
        foreach($p_cat_ids as $p_cat_idsval){
            $valget = explode("=", $p_cat_idsval);
            $p_cat_ids_arr[] = $valget[1];
        }
    }

    $perpage = $_REQUEST['perpage'];
    $args = array(
        'post_type'              => array('product'),
        'post_status'            => array('Publish'),
        'posts_per_page'         => $perpage,
        'paged'                  => $_REQUEST['setpage']
    );
    
    $conditinalarr = array('relation' => 'AND');
    
    if($_REQUEST['p_cat_ids'] != ""){
        if(count($p_cat_ids_arr) > 0){
            $conditinalarr[] = array(
                'taxonomy' => 'product_cat',
                'field'    => 'id',
                'terms'    => $p_cat_ids_arr
            );
        }
    }
    
    if(count($conditinalarr) > 1){
        $args['tax_query'] = $conditinalarr;
    }
    
    $query = new WP_Query($args);
    $trecord = $query->post_count;
    $tpage = $query->max_num_pages;

    if ($query->have_posts()) {
        do_action('woocommerce_before_shop_loop');
        woocommerce_product_loop_start();
        
        while ($query->have_posts()) {
            $query->the_post();
            do_action('woocommerce_shop_loop');
            wc_get_template_part('content', 'product');
        }
        
        woocommerce_product_loop_end();    
        do_action('woocommerce_after_shop_loop');    
    } else {
        echo "No products were found matching your selection.";
    }

    wp_reset_postdata();
    wp_die(); 
}

// Register AJAX actions
add_action('wp_ajax_nopriv_product_results_filters_ajax', 'fun_product_results_filters_ajax');
add_action('wp_ajax_product_results_filters_ajax', 'fun_product_results_filters_ajax');
?>

This ensures your filtering works seamlessly with AJAX.


Conclusion

By following these steps, you can implement a custom WooCommerce product filter that enhances user experience while maintaining site performance. This AJAX-powered solution eliminates the need for additional plugins and ensures smooth functionality.


FAQ

What types of posts can I filter using this method?

You can filter any custom post types, including WooCommerce products, blog posts, or any other post types defined in your WordPress site.

How can I add more filter options?

You can expand the filtering options by adding more checkboxes or dropdowns in the widget code. Just make sure to update the corresponding JavaScript and PHP code to handle the new filters.

Is it compatible with all themes?

Most themes should be compatible, especially if they support WooCommerce. However, some customization might be needed depending on your theme’s structure.

Can I use this filtering method on non-WooCommerce post types?

Yes, you can adapt the code for any post type. Just change the post_type parameter in the PHP query to your desired post type.

How can I style the filter widget?

You can use CSS to style the filter widget according to your website’s design. Modify the existing classes or add new styles to match your theme.


I’m a WordPress developer with 10+ years of experience in WooCommerce and custom plugins. I combine technical expertise with design flair to help you create standout, user-friendly websites. Let’s transform your digital presence!

This Post Has 0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Back To Top