فیلتر محصولات ووکامرس با شورتکد
این کد یک سیستم فیلتر سفارشی برای محصولات ووکامرس ایجاد میکند که با قرار دادن شورتکد زیر در صفحه، قابل استفاده است:
[product_filter]
این فیلتر شامل محدوده قیمت، مرتبسازی محصولات و ویژگیهای محصول است. محدوده قیمت بهصورت اسلایدر دوطرفه نمایش داده میشود و حداقل و حداکثر قیمت نیز بهصورت خودکار از محصولات موجود در فروشگاه دریافت میشود.
گزینههای مرتبسازی شامل پیشفرض، محبوبترین، دارای بالاترین امتیاز، جدیدترین، ارزانترین و گرانترین محصولات است.
همچنین تمام ویژگیهای ثبتشده در ووکامرس که دارای مقدار و محصول هستند، بهصورت خودکار در فیلتر نمایش داده میشوند.
فیلترهای انتخابشده در بالای پنجره نمایش داده شده و امکان حذف هر فیلتر بهصورت جداگانه یا پاک کردن همه فیلترها وجود دارد. ظاهر فیلتر نیز بهصورت کاملاً ریسپانسیو طراحی شده و در موبایل به شکل پنجره کشویی از پایین صفحه نمایش داده میشود.
در نهایت، انتخابهای کاربر از طریق پارامترهای URL به کوئری محصولات ووکامرس اعمال میشوند و نیازی به افزونه فیلتر محصولات نیست.
<?php
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
add_shortcode( 'product_filter', 'render_product_filter' );
function render_product_filter() {
global $wpdb;
$default_orderby = apply_filters(
'woocommerce_default_catalog_orderby',
'menu_order'
);
$allowed_orderby = array(
'menu_order',
'popularity',
'rating',
'date',
'price',
'price-desc',
);
$orderby = $default_orderby;
if ( isset( $_GET['orderby'] ) && is_string( $_GET['orderby'] ) ) {
$requested_orderby = sanitize_key( wp_unslash( $_GET['orderby'] ) );
if ( in_array( $requested_orderby, $allowed_orderby, true ) ) {
$orderby = $requested_orderby;
}
}
$current_min = 0;
$current_max = 0;
if ( isset( $_GET['min_price'] ) && is_scalar( $_GET['min_price'] ) ) {
$current_min = absint( wp_unslash( $_GET['min_price'] ) );
}
if ( isset( $_GET['max_price'] ) && is_scalar( $_GET['max_price'] ) ) {
$current_max = absint( wp_unslash( $_GET['max_price'] ) );
}
$min_price_db = $wpdb->get_var(
"
SELECT MIN(CAST(pm.meta_value AS DECIMAL(20,4)))
FROM {$wpdb->postmeta} AS pm
INNER JOIN {$wpdb->posts} AS p
ON p.ID = pm.post_id
WHERE pm.meta_key = '_price'
AND pm.meta_value <> ''
AND p.post_type IN ('product', 'product_variation')
AND p.post_status = 'publish'
"
);
$max_price_db = $wpdb->get_var(
"
SELECT MAX(CAST(pm.meta_value AS DECIMAL(20,4)))
FROM {$wpdb->postmeta} AS pm
INNER JOIN {$wpdb->posts} AS p
ON p.ID = pm.post_id
WHERE pm.meta_key = '_price'
AND pm.meta_value <> ''
AND p.post_type IN ('product', 'product_variation')
AND p.post_status = 'publish'
"
);
$min_price_db = $min_price_db !== null
? (float) $min_price_db
: 0;
$max_price_db = $max_price_db !== null
? (float) $max_price_db
: 1000000;
$min_price_db = (int) floor( $min_price_db );
$max_price_db = (int) ceil( $max_price_db );
if ( $max_price_db <= $min_price_db ) {
$max_price_db = $min_price_db + 1000;
}
if ( $current_min <= 0 ) {
$current_min = $min_price_db;
}
if ( $current_max <= 0 ) {
$current_max = $max_price_db;
}
$current_min = max(
$min_price_db,
min( $current_min, $max_price_db )
);
$current_max = max(
$min_price_db,
min( $current_max, $max_price_db )
);
if ( $current_min > $current_max ) {
$current_min = $current_max;
}
$attributes = wc_get_attribute_taxonomies();
$filterable_attributes = array();
foreach ( $attributes as $attribute ) {
$taxonomy_name = wc_attribute_taxonomy_name(
$attribute->attribute_name
);
$terms = get_terms(
array(
'taxonomy' => $taxonomy_name,
'hide_empty' => true,
)
);
if ( ! is_wp_error( $terms ) && ! empty( $terms ) ) {
$filterable_attributes[] = array(
'name' => $attribute->attribute_label,
'slug' => $attribute->attribute_name,
'taxonomy' => $taxonomy_name,
'terms' => $terms,
);
}
}
$sort_options = apply_filters(
'woocommerce_catalog_orderby',
array(
'menu_order' => __( 'پیشفرض', 'woocommerce' ),
'popularity' => __( 'محبوبیت', 'woocommerce' ),
'rating' => __( 'امتیاز', 'woocommerce' ),
'date' => __( 'جدیدترین', 'woocommerce' ),
'price' => __( 'ارزانترین', 'woocommerce' ),
'price-desc' => __( 'گرانترین', 'woocommerce' ),
)
);
$active_filters_count = 0;
$active_filters_list = array();
$active_filters_params = array();
if (
isset( $_GET['min_price'] ) ||
isset( $_GET['max_price'] )
) {
$active_filters_count++;
$active_filters_list[] = 'قیمت';
$active_filters_params[] = array(
'name' => 'قیمت',
'params' => array(
'min_price',
'max_price',
),
);
}
if (
isset( $_GET['orderby'] ) &&
is_string( $_GET['orderby'] ) &&
$orderby !== 'menu_order'
) {
$active_filters_count++;
$active_filters_list[] = 'مرتبسازی';
$active_filters_params[] = array(
'name' => 'مرتبسازی',
'params' => array( 'orderby' ),
);
}
foreach ( $attributes as $attribute ) {
$filter_key = 'filter_' . $attribute->attribute_name;
if (
isset( $_GET[ $filter_key ] ) &&
is_scalar( $_GET[ $filter_key ] ) &&
$_GET[ $filter_key ] !== ''
) {
$active_filters_count++;
$active_filters_list[] = $attribute->attribute_label;
$active_filters_params[] = array(
'name' => $attribute->attribute_label,
'params' => array( $filter_key ),
);
}
}
ob_start();
?>
<div class="pf-container">
<button
class="pf-toggle <?php echo $active_filters_count > 0 ? 'pf-active-filter' : ''; ?>"
onclick="document.getElementById('pf-modal').classList.add('pf-active'); document.body.style.overflow = 'hidden';"
>
<svg
width="18"
height="18"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
>
<line x1="4" y1="6" x2="20" y2="6"/>
<line x1="4" y1="12" x2="20" y2="12"/>
<line x1="4" y1="18" x2="20" y2="18"/>
<circle cx="8" cy="6" r="2"/>
<circle cx="16" cy="12" r="2"/>
<circle cx="10" cy="18" r="2"/>
</svg>
<?php
echo $active_filters_count > 0
? 'فیلتر فعال (' . $active_filters_count . ')'
: 'فیلتر';
?>
</button>
<div
id="pf-modal"
class="pf-modal"
onclick="if(event.target === this) { this.classList.remove('pf-active'); document.body.style.overflow = ''; }"
>
<div class="pf-modal-content">
<div class="pf-header">
<h3>فیلتر محصولات</h3>
<button
class="pf-close"
type="button"
onclick="document.getElementById('pf-modal').classList.remove('pf-active'); document.body.style.overflow = '';"
>
×
</button>
</div>
<?php if ( $active_filters_count > 0 ) : ?>
<div class="pf-active-tags">
<span class="pf-active-tags-title">
فیلترهای فعال:
</span>
<?php foreach ( $active_filters_params as $filter ) : ?>
<span class="pf-tag">
<?php echo esc_html( $filter['name'] ); ?>
<a
href="<?php echo esc_url( remove_query_arg( $filter['params'] ) ); ?>"
class="pf-tag-remove"
title="حذف این فیلتر"
>
×
</a>
</span>
<?php endforeach; ?>
</div>
<?php endif; ?>
<form
class="pf-form"
method="get"
id="pf-form"
>
<div class="pf-section">
<label class="pf-price-label">
محدوده قیمت
</label>
<div class="pf-slider-container">
<div class="pf-slider-values">
<span
class="pf-price-box"
id="pf-min-display"
>
<?php echo esc_html( number_format_i18n( $current_min ) ); ?>
</span>
<span class="pf-price-sep">
تا
</span>
<span
class="pf-price-box"
id="pf-max-display"
>
<?php echo esc_html( number_format_i18n( $current_max ) ); ?>
</span>
<span class="pf-price-unit">
تومان
</span>
</div>
<div class="pf-slider-track">
<div
class="pf-slider-range"
id="pf-slider-range"
></div>
<input
type="range"
id="pf-min-slider"
min="<?php echo esc_attr( $min_price_db ); ?>"
max="<?php echo esc_attr( $max_price_db ); ?>"
value="<?php echo esc_attr( $current_min ); ?>"
step="1000"
class="pf-slider pf-slider-min"
dir="rtl"
>
<input
type="range"
id="pf-max-slider"
min="<?php echo esc_attr( $min_price_db ); ?>"
max="<?php echo esc_attr( $max_price_db ); ?>"
value="<?php echo esc_attr( $current_max ); ?>"
step="1000"
class="pf-slider pf-slider-max"
dir="rtl"
>
</div>
<input
type="hidden"
name="min_price"
id="pf-min-price"
value="<?php echo esc_attr( $current_min ); ?>"
>
<input
type="hidden"
name="max_price"
id="pf-max-price"
value="<?php echo esc_attr( $current_max ); ?>"
>
</div>
</div>
<div class="pf-section">
<select
name="orderby"
class="pf-select pf-label-select"
>
<option
value=""
disabled
<?php selected( $orderby, '' ); ?>
class="pf-label-option"
>
مرتبسازی محصولات
</option>
<?php foreach ( $sort_options as $id => $name ) : ?>
<?php
if ( ! in_array( $id, $allowed_orderby, true ) ) {
continue;
}
?>
<option
value="<?php echo esc_attr( $id ); ?>"
<?php selected( $orderby, $id ); ?>
>
<?php echo esc_html( $name ); ?>
</option>
<?php endforeach; ?>
</select>
</div>
<?php foreach ( $filterable_attributes as $attr ) : ?>
<?php
$filter_key = 'filter_' . $attr['slug'];
$current_attr = '';
if (
isset( $_GET[ $filter_key ] ) &&
is_scalar( $_GET[ $filter_key ] )
) {
$current_attr = sanitize_title(
wp_unslash( $_GET[ $filter_key ] )
);
}
?>
<div class="pf-section">
<select
name="<?php echo esc_attr( $filter_key ); ?>"
class="pf-select pf-label-select"
>
<option
value=""
<?php selected( $current_attr, '' ); ?>
class="pf-label-option"
>
<?php echo esc_html( $attr['name'] ); ?>
</option>
<?php foreach ( $attr['terms'] as $term ) : ?>
<option
value="<?php echo esc_attr( $term->slug ); ?>"
<?php selected( $current_attr, $term->slug ); ?>
>
<?php echo esc_html( $term->name ); ?>
</option>
<?php endforeach; ?>
</select>
</div>
<?php endforeach; ?>
<div class="pf-actions">
<button type="submit">
اعمال فیلتر
</button>
<button
type="button"
id="pf-reset-btn"
onclick="resetAndSubmit()"
>
پاک کردن همه
</button>
</div>
</form>
</div>
</div>
</div>
<style>
.pf-container {
font-family: inherit;
direction: rtl;
}
.pf-toggle {
display: inline-flex;
align-items: center;
gap: 5px;
vertical-align: middle;
outline: none;
}
.pf-toggle.pf-active-filter {
background: #4CAF50;
}
.pf-toggle.pf-active-filter:hover {
background: #388E3C;
}
.pf-modal {
display: none;
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(0,0,0,0.4);
z-index: 2;
justify-content: center;
align-items: center;
}
.pf-modal.pf-active {
display: flex;
}
.pf-modal-content {
background: #fff;
border-radius: 10px;
padding: 20px;
width: 90%;
max-width: 400px;
max-height: 90vh;
overflow-y: auto;
box-shadow: 0 20px 60px rgba(0,0,0,0.15);
animation: pfFadeIn 0.3s ease;
}
@keyframes pfFadeIn {
from {
opacity: 0;
transform: scale(0.95);
}
to {
opacity: 1;
transform: scale(1);
}
}
.pf-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 10px;
border-bottom: 1px solid #e0e0e0;
padding-bottom: 10px;
margin-left: -20px;
margin-right: -20px;
padding-left: 20px;
padding-right: 20px;
}
.pf-header h3 {
margin: 0;
font-size: 16px;
color: #333;
}
.pf-close {
background: none;
border: none;
font-size: 28px;
color: #999;
cursor: pointer;
line-height: 1;
padding: 0;
}
.pf-close:hover {
color: #333;
}
.pf-active-tags {
display: flex;
flex-wrap: wrap;
gap: 5px;
margin-bottom: 12px;
padding-bottom: 10px;
border-bottom: 1px solid #f0f0f0;
align-items: center;
}
.pf-active-tags-title {
font-size: 12px;
color: #666;
font-weight: 500;
margin-left: 5px;
}
.pf-tag {
display: inline-flex;
align-items: center;
gap: 4px;
padding: 4px 10px;
background: #e8f5e9;
color: #2e7d32;
border-radius: 3px;
font-size: 12px;
text-decoration: none;
}
.pf-tag-remove {
color: #c62828;
text-decoration: none;
font-size: 16px;
font-weight: bold;
cursor: pointer;
line-height: 1;
}
.pf-tag-remove:hover {
color: #b71c1c;
}
.pf-form {
display: flex;
flex-direction: column;
gap: 12px;
}
.pf-section {
display: flex;
flex-direction: column;
gap: 5px;
}
.pf-select,
.pf-input {
width: 100%;
padding: 10px 12px;
border: 1px solid #e0e0e0;
border-radius: 5px;
font-size: 14px;
color: #333;
background: #fafafa;
outline: none;
transition: border-color 0.3s;
box-sizing: border-box;
appearance: none;
-webkit-appearance: none;
-moz-appearance: none;
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24' fill='none' stroke='%23999' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='6 9 12 15 18 9'%3E%3C/polyline%3E%3C/svg%3E");
background-repeat: no-repeat;
background-position: left 10px center;
background-size: 12px;
padding-left: 30px;
}
.pf-label-select .pf-label-option {
color: #E91E63 !important;
font-weight: 500;
}
.pf-label-select option:first-child {
color: #E91E63;
}
.pf-price-label {
font-size: 13px;
color: #E91E63;
font-weight: 500;
margin-bottom: 2px;
}
.pf-slider-container {
padding: 10px 0;
}
.pf-slider-values {
display: flex;
justify-content: center;
align-items: center;
gap: 8px;
font-size: 13px;
color: #333;
margin-bottom: 15px;
}
.pf-price-box {
background: linear-gradient(135deg, #7F54B3, #9C27B0);
color: #fff;
padding: 4px 12px;
border-radius: 20px;
font-weight: 600;
font-size: 13px;
box-shadow: 0 2px 8px rgba(127, 84, 179, 0.3);
}
.pf-price-sep {
color: #999;
font-weight: 500;
}
.pf-price-unit {
color: #666;
font-size: 12px;
}
.pf-slider-track {
position: relative;
height: 6px;
background: #e0e0e0;
border-radius: 10px;
margin: 0 8px;
direction: rtl;
}
.pf-slider-range {
position: absolute;
height: 100%;
background: linear-gradient(90deg, #7F54B3, #9C27B0);
border-radius: 10px;
z-index: 2;
}
.pf-slider {
position: absolute;
width: 100%;
height: 6px;
-webkit-appearance: none;
appearance: none;
background: transparent;
outline: none;
pointer-events: none;
top: 0;
z-index: 2;
direction: rtl;
}
.pf-slider::-webkit-slider-thumb {
-webkit-appearance: none;
appearance: none;
width: 22px;
height: 22px;
background: linear-gradient(135deg, #7F54B3, #9C27B0);
border-radius: 50%;
cursor: pointer;
pointer-events: auto;
border: 3px solid #fff;
box-shadow: 0 2px 10px rgba(127, 84, 179, 0.4);
transition: transform 0.2s, box-shadow 0.2s;
}
.pf-slider::-webkit-slider-thumb:hover {
transform: scale(1.15);
box-shadow: 0 4px 15px rgba(127, 84, 179, 0.5);
}
.pf-slider::-moz-range-thumb {
width: 22px;
height: 22px;
background: linear-gradient(135deg, #7F54B3, #9C27B0);
border-radius: 50%;
cursor: pointer;
pointer-events: auto;
border: 3px solid #fff;
box-shadow: 0 2px 10px rgba(127, 84, 179, 0.4);
transition: transform 0.2s, box-shadow 0.2s;
}
.pf-slider::-moz-range-thumb:hover {
transform: scale(1.15);
box-shadow: 0 4px 15px rgba(127, 84, 179, 0.5);
}
.pf-actions {
display: flex;
gap: 8px;
margin-top: 0;
}
@media (max-width: 768px) {
.pf-modal {
align-items: flex-end;
}
.pf-modal-content {
width: 100%;
max-width: 100%;
border-radius: 15px 15px 0 0;
max-height: 85vh;
padding: 20px;
animation: pfSlideUp 0.4s ease;
}
@keyframes pfSlideUp {
from {
transform: translateY(100%);
opacity: 0;
}
to {
transform: translateY(0);
opacity: 1;
}
}
.pf-submit,
.pf-reset {
padding: 10px 10px !important;
font-size: 14px !important;
border-radius: 5px !important;
}
.pf-slider::-webkit-slider-thumb {
width: 26px;
height: 26px;
}
.pf-slider::-moz-range-thumb {
width: 26px;
height: 26px;
}
}
</style>
<script>
function resetAndSubmit() {
const form = document.getElementById('pf-form');
if (!form) {
return;
}
const url = new URL(window.location.href);
url.search = '';
window.location.href = url.toString();
}
function updateSliderRange() {
const minSlider = document.getElementById('pf-min-slider');
const maxSlider = document.getElementById('pf-max-slider');
const range = document.getElementById('pf-slider-range');
if (!minSlider || !maxSlider || !range) {
return;
}
const minVal = parseInt(minSlider.value, 10);
const maxVal = parseInt(maxSlider.value, 10);
const min = parseInt(minSlider.min, 10);
const max = parseInt(minSlider.max, 10);
if (max <= min) {
range.style.right = '0%';
range.style.width = '100%';
return;
}
const percentMin =
((minVal - min) / (max - min)) * 100;
const percentMax =
((maxVal - min) / (max - min)) * 100;
range.style.right =
Math.max(0, Math.min(100, percentMin)) + '%';
range.style.width =
Math.max(0, Math.min(100, percentMax - percentMin)) + '%';
}
document.addEventListener('DOMContentLoaded', function() {
const minSlider =
document.getElementById('pf-min-slider');
const maxSlider =
document.getElementById('pf-max-slider');
const minDisplay =
document.getElementById('pf-min-display');
const maxDisplay =
document.getElementById('pf-max-display');
const minPrice =
document.getElementById('pf-min-price');
const maxPrice =
document.getElementById('pf-max-price');
if (
!minSlider ||
!maxSlider ||
!minDisplay ||
!maxDisplay ||
!minPrice ||
!maxPrice
) {
return;
}
function formatNumber(num) {
return Number(num).toLocaleString('fa-IR');
}
function updateSliders() {
let minVal =
parseInt(minSlider.value, 10);
let maxVal =
parseInt(maxSlider.value, 10);
if (minVal > maxVal) {
if (this === minSlider) {
minSlider.value = maxVal;
minVal = maxVal;
} else {
maxSlider.value = minVal;
maxVal = minVal;
}
}
minDisplay.textContent =
formatNumber(minVal);
maxDisplay.textContent =
formatNumber(maxVal);
minPrice.value =
minVal;
maxPrice.value =
maxVal;
updateSliderRange();
}
minSlider.addEventListener(
'input',
updateSliders
);
maxSlider.addEventListener(
'input',
updateSliders
);
updateSliderRange();
});
</script>
<?php
return ob_get_clean();
}
add_action(
'woocommerce_product_query',
'pf_apply_dynamic_filters'
);
function pf_apply_dynamic_filters( $q ) {
$tax_query = $q->get( 'tax_query' );
if ( empty( $tax_query ) || ! is_array( $tax_query ) ) {
$tax_query = array();
}
$attributes = wc_get_attribute_taxonomies();
foreach ( $attributes as $attribute ) {
$filter_key =
'filter_' . $attribute->attribute_name;
if (
! isset( $_GET[ $filter_key ] ) ||
! is_scalar( $_GET[ $filter_key ] )
) {
continue;
}
$value =
sanitize_title(
wp_unslash( $_GET[ $filter_key ] )
);
if ( $value === '' ) {
continue;
}
$tax_query[] = array(
'taxonomy' =>
wc_attribute_taxonomy_name(
$attribute->attribute_name
),
'field' => 'slug',
'terms' => $value,
'operator' => 'IN',
);
}
if ( ! empty( $tax_query ) ) {
$q->set(
'tax_query',
$tax_query
);
}
}