Introduction When running an eCommerce site using WooCommerce, the cart page plays a vital role…
How to Implement a Custom WooCommerce Product Filter by Categories with AJAX
Many websites need the ability to filter WordPress posts to display dynamic content and improve user experience. Traditionally, this has been achieved through plugins. However, plugins often add extra features and code that may clutter your site and slow it down. While plugins can be useful, they aren’t always necessary for straightforward tasks like post filtering. Therefore, in this article, we’ll show you how to effectively filter WordPress posts using AJAX (Asynchronous JavaScript and XML) without relying on additional plugins.
Specifically, AJAX allows you to update specific areas of your webpage without reloading the entire page. Consequently, this approach keeps your site responsive and lightweight while simplifying the process. Let’s get started!
Why Avoid Plugins for Filtering
There are several reasons to consider filtering without plugins:
- Performance Impact: Plugins can slow down your site due to added overhead and unnecessary features. Thus, eliminating plugins can enhance performance.
- Compatibility Issues: Plugins may conflict with other site elements or future WordPress updates. As a result, this can lead to unexpected problems that disrupt user experience.
- Maintenance Overhead: Regular updates and potential security vulnerabilities from plugins can add extra work to your maintenance routine. Therefore, minimizing reliance on plugins reduces this burden.
By filtering posts without plugins, you can avoid these issues and keep your site running smoothly.
Creating a Filter for WooCommerce Products
In this example, we’ll create a filter for WooCommerce products based on categories. This will demonstrate how filtering works with WooCommerce categories while using both OR and AND operators to ensure precise results. Let’s dive in!
Adding the Filter Widget code
To create a WooCommerce Product Filter with checkboxes, you first need to set up a widget that allows users to select the categories they want to filter by. Below is the PHP code to generate a category filter widget for your site:
<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 Code – Adding AJAX Functionality
Next, you’ll need some JavaScript to manage the filtering process asynchronously. This script listens for changes in the checkboxes and updates the product results without reloading the page. Here’s how to set that up:
<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
To handle the AJAX request and return the filtered products, you’ll need to add a PHP function to your theme’s functions.php
file. This function processes the selected categories and fetches the relevant products. Here’s how to set it up:
<?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 the steps outlined above, you’ll have a user-friendly, AJAX-based product filter for your WooCommerce store. This feature allows customers to quickly filter products by category without reloading the page, significantly enhancing their shopping experience.
Feel free to customize the code to fit your specific needs and styling preferences. If you have any questions or encounter issues, please reach out or leave a comment below.
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.
This Post Has 0 Comments