You can create a WooCommerce filter plugin that allows users to filter products by category and tags. Here’s a basic approach to achieve that:
Steps to Create a WooCommerce Filter Plugin:
1. Create a Plugin
You can start by creating a simple plugin structure:
- Create a folder named
woocommerce-filter-plugin
. - Inside the folder, create a file called
woocommerce-filter-plugin.php
.
Below is a complete implementation of the WooCommerce filter plugin with proper error handling and a structured approach where the files are organized within the plugin folder. The structure includes separate files for the main plugin, JavaScript, and CSS.
Plugin Folder Structure:
woocommerce-filter-plugin/
│
├── assets/
│ ├── css/
│ │ └── style.css
│ └── js/
│ └── filter.js
│
├── includes/
│ └── filter-functions.php
│
├── woocommerce-filter-plugin.php
└── readme.txt
1. woocommerce-filter-plugin.php
(Main Plugin File)
<?php
/**
* Plugin Name: WooCommerce Filter Plugin
* Description: A custom plugin to filter WooCommerce products by category and tags.
* Version: 1.0
* Author: Your Name
* Text Domain: woocommerce-filter-plugin
*/
// Exit if accessed directly
if (!defined('ABSPATH')) {
exit;
}
// Include the necessary filter functions
require_once plugin_dir_path(__FILE__) . 'includes/filter-functions.php';
// Register and enqueue styles and scripts
function wc_filter_enqueue_scripts() {
// Enqueue CSS
wp_enqueue_style('wc-filter-css', plugin_dir_url(__FILE__) . 'assets/css/style.css', array(), '1.0');
// Enqueue JS
wp_enqueue_script('wc-filter-js', plugin_dir_url(__FILE__) . 'assets/js/filter.js', array('jquery'), '1.0', true);
// Localize Ajax URL for use in JS
wp_localize_script('wc-filter-js', 'wcFilterAjax', array(
'ajaxurl' => admin_url('admin-ajax.php')
));
}
add_action('wp_enqueue_scripts', 'wc_filter_enqueue_scripts');
// Add the shortcode for the filter form
add_shortcode('woocommerce_product_filter', 'wc_product_filter_form');
2. includes/filter-functions.php
(Plugin Logic and Functions)
<?php
// Exit if accessed directly
if (!defined('ABSPATH')) {
exit;
}
// Display the filter form
function wc_product_filter_form() {
// Get categories and tags
$categories = get_terms('product_cat', array('hide_empty' => true));
$tags = get_terms('product_tag', array('hide_empty' => true));
ob_start();
?>
<form id="product-filter-form" method="GET">
<select name="category" id="category-filter">
<option value=""><?php _e('Select Category', 'woocommerce-filter-plugin'); ?></option>
<?php foreach ($categories as $category) : ?>
<option value="<?php echo esc_attr($category->slug); ?>"><?php echo esc_html($category->name); ?></option>
<?php endforeach; ?>
</select>
<select name="tag" id="tag-filter">
<option value=""><?php _e('Select Tag', 'woocommerce-filter-plugin'); ?></option>
<?php foreach ($tags as $tag) : ?>
<option value="<?php echo esc_attr($tag->slug); ?>"><?php echo esc_html($tag->name); ?></option>
<?php endforeach; ?>
</select>
<button type="submit"><?php _e('Filter', 'woocommerce-filter-plugin'); ?></button>
</form>
<div id="filtered-products">
<?php wc_filter_products(); ?>
</div>
<?php
return ob_get_clean();
}
// Function to fetch and display filtered products
function wc_filter_products() {
$category = isset($_GET['category']) ? sanitize_text_field($_GET['category']) : '';
$tag = isset($_GET['tag']) ? sanitize_text_field($_GET['tag']) : '';
$args = array(
'post_type' => 'product',
'posts_per_page' => -1,
'tax_query' => array(
'relation' => 'AND',
),
);
if (!empty($category)) {
$args['tax_query'][] = array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => $category,
);
}
if (!empty($tag)) {
$args['tax_query'][] = array(
'taxonomy' => 'product_tag',
'field' => 'slug',
'terms' => $tag,
);
}
$query = new WP_Query($args);
if ($query->have_posts()) {
while ($query->have_posts()) {
$query->the_post();
wc_get_template_part('content', 'product');
}
} else {
echo '<p>' . __('No products found', 'woocommerce-filter-plugin') . '</p>';
}
wp_reset_postdata();
}
// AJAX handling for dynamic filtering (optional)
add_action('wp_ajax_wc_filter_products', 'wc_filter_products');
add_action('wp_ajax_nopriv_wc_filter_products', 'wc_filter_products');
3. assets/js/filter.js
(JavaScript for AJAX Filtering)
jQuery(document).ready(function($) {
$('#product-filter-form').on('submit', function(e) {
e.preventDefault();
var form = $(this);
var category = $('#category-filter').val();
var tag = $('#tag-filter').val();
$.ajax({
url: wcFilterAjax.ajaxurl,
type: 'GET',
data: {
action: 'wc_filter_products',
category: category,
tag: tag
},
success: function(response) {
$('#filtered-products').html(response);
},
error: function(xhr, status, error) {
alert('Something went wrong. Please try again.');
}
});
});
});
4. assets/css/style.css
(Basic Styling for the Filter Form)
#product-filter-form {
margin-bottom: 20px;
}
#product-filter-form select {
margin-right: 10px;
}
#product-filter-form button {
background-color: #333;
color: #fff;
border: none;
padding: 8px 15px;
cursor: pointer;
}
#product-filter-form button:hover {
background-color: #555;
}
5. readme.txt
(Optional)
=== WooCommerce Filter Plugin ===
Contributors: Your Name
Tags: woocommerce, filter, category, tag, ajax
Requires at least: 5.0
Tested up to: 6.0
Stable tag: 1.0
License: GPLv2 or later
License URI: https://www.gnu.org/licenses/gpl-2.0.html
A WooCommerce filter plugin to filter products by category and tags.
== Installation ==
1. Upload the `woocommerce-filter-plugin` folder to the `/wp-content/plugins/` directory.
2. Activate the plugin through the 'Plugins' menu in WordPress.
3. Use the `[woocommerce_product_filter]` shortcode on any page to display the product filter form.
Error Handling:
- Input Sanitization: Inputs from the filter form (
category
andtag
) are sanitized usingsanitize_text_field()
. - AJAX Error Handling: If the AJAX request fails, an error message is displayed to the user.
- Fallback: If no products are found, a friendly “No products found” message is displayed.
How it Works:
- A shortcode
[woocommerce_product_filter]
is created that can be placed on any page. - The plugin generates a form with category and tag dropdowns.
- Upon submission, it fetches the products matching the selected category and/or tag.
- (Optional) AJAX can be used to load products dynamically.
Installation:
- Upload the plugin folder (
woocommerce-filter-plugin
) to the/wp-content/plugins/
directory. - Activate the plugin from the WordPress admin.
- Use the
[woocommerce_product_filter]
shortcode to display the filter on any page.
Leave a Reply