Например, предположим, что у продуктов есть такие атрибуты, как страна, бренд и мощность. . Когда пользователь выбирает «Франция» в качестве атрибута страны, на странице списка продуктов должны отображаться только товары, для которых в качестве страны установлено значение «Франция». Кроме того, фильтры бренда и мощности должны обновиться, чтобы отображать только варианты, доступные для товаров из Франции.
С уважением,
Мне удалось добиться этого с помощью действия woocommerce_product_query и функции $query->set('tax_query', ...). Вот решение:
Код: Выделить всё
add_action('woocommerce_product_query', 'custom_filter_woocommerce_products', 10, 2);
function custom_filter_woocommerce_products($query)
{
// Check if we are on a product archive page
if (is_shop() || is_product_category() || is_product_tag()) {
// Get selected attributes from URL
$selected_attributes = [];
// Get all registered attribute taxonomies
$attribute_taxonomies = wc_get_attribute_taxonomies();
// Loop through each attribute taxonomy to check if it's set in the URL
foreach ($attribute_taxonomies as $attribute) {
$taxonomy = wc_attribute_taxonomy_name($attribute->attribute_name);
$taxonomy = str_replace('pa_', 'filter_', $taxonomy);
// Check if this taxonomy is set in the URL
if (isset($_GET[$taxonomy])) {
$terms = explode(',', $_GET[$taxonomy]);
$selected_attributes[$taxonomy] = array_map('sanitize_text_field', $terms);
}
}
if (!empty($selected_attributes)) {
$tax_query = [];
// Loop through selected attributes and build tax query
foreach ($selected_attributes as $taxonomy => $terms) {
$taxonomy = str_replace('filter_', 'pa_', $taxonomy);
$tax_query[] = [
'taxonomy' => $taxonomy,
'field' => 'slug',
'terms' => $terms,
'operator' => 'IN',
];
}
// Apply the tax queries to main query
if (!empty($tax_query)) {
$tax_query['relation'] = 'AND';
$query->set('tax_query', $tax_query);
}
}
}
}
Подробнее здесь: https://stackoverflow.com/questions/786 ... lationship
Мобильная версия