Почему в Woocommerce не работает фильтр по категориям?Php

Кемеровские программисты php общаются здесь
Ответить
Anonymous
 Почему в Woocommerce не работает фильтр по категориям?

Сообщение Anonymous »

Я пытаюсь создать фильтр для продуктов в woocommerce по атрибутам, но не могу устранить ошибку.
Существует функция для создания контейнера для фильтра перед циклом продукта, и есть функция для фильтрации. Почему не работает фильтр по категориям (/product-category/cloth/)? Но работает корректно на главной странице магазина (/shop/):
function add_container_for_filters() {
echo '';
echo 'Filters';
echo '';

// Get shop page
if ( is_shop() ) {
// Color filter
echo '';
echo 'Color';
// Retrieve terms for color attribute
$colors = get_terms( 'pa_color', array( 'hide_empty' => true ) );
foreach ( $colors as $color ) {
// Check if color filter is currently selected
$checked = isset( $_GET['color'] ) && in_array( $color->slug, (array) $_GET['color'] ) ? 'checked' : '';
echo '' . esc_html( $color->name ) . '';
}
echo '';

// Size filter
echo '';
echo 'Size';
// Retrieve terms for size attribute
$sizes = get_terms( 'pa_size', array( 'hide_empty' => true ) );
foreach ( $sizes as $size ) {
// Check if size filter is currently selected
$checked = isset( $_GET['size'] ) && in_array( $size->slug, (array) $_GET['size'] ) ? 'checked' : '';
echo '' . esc_html( $size->name ) . '';
}
echo '';
}

// Get current category
if ( is_product_category() ) {
$term = get_queried_object();
$term_id = $term->term_id;

// Query products in the current category
$args = array(
'post_type' => 'product',
'posts_per_page' => -1,
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'field' => 'term_id',
'terms' => $term_id,
),
),
);
$query = new WP_Query( $args );

// Store product IDs
$product_ids = array();
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
$product_ids[] = get_the_ID();
}
wp_reset_postdata();
}

// Retrieve terms for color attribute present in filtered products
if ( ! empty( $product_ids ) ) {
$colors = wp_get_object_terms( $product_ids, 'pa_color', array( 'hide_empty' => true ) );
if ( ! empty( $colors ) && ! is_wp_error( $colors ) ) {
echo '';
echo 'Color';
foreach ( $colors as $color ) {
$checked = isset( $_GET['color'] ) && in_array( $color->slug, (array) $_GET['color'] ) ? 'checked' : '';
echo '' . esc_html( $color->name ) . '';
}
echo '';
}

// Retrieve terms for size attribute present in filtered products
$sizes = wp_get_object_terms( $product_ids, 'pa_size', array( 'hide_empty' => true ) );
if ( ! empty( $sizes ) && ! is_wp_error( $sizes ) ) {
echo '';
echo 'Size';
foreach ( $sizes as $size ) {
$checked = isset( $_GET['size'] ) && in_array( $size->slug, (array) $_GET['size'] ) ? 'checked' : '';
echo '' . esc_html( $size->name ) . '';
}
echo '';
}
}
}

// Apply filters button
echo 'Apply Filters';

// Clear Filters button
echo 'Clear Filters';
echo '';
}
add_action('woocommerce_before_shop_loop', 'add_container_for_filters');

// function for filteging
add_action('woocommerce_product_query', 'filter_products_by_attributes');
function filter_products_by_attributes($q) {
if (is_shop() || is_product_category()) {
// Check if any filters are applied
if (isset($_GET['size']) || isset($_GET['color'])) {
// Initialize the tax query array
$tax_query = array('relation' => 'AND');

// Color filter
if (isset($_GET['color']) && is_array($_GET['color'])) {
$color_filter = array_map('sanitize_text_field', $_GET['color']);
if (!empty($color_filter)) {
$tax_query[] = array(
'taxonomy' => 'pa_color',
'field' => 'slug',
'terms' => $color_filter,
'operator' => 'IN',
);
}
}

// Size filter
if (isset($_GET['size']) && is_array($_GET['size'])) {
$size_filter = array_map('sanitize_text_field', $_GET['size']);
if (!empty($size_filter)) {
$tax_query[] = array(
'taxonomy' => 'pa_size',
'field' => 'slug',
'terms' => $size_filter,
'operator' => 'IN',
);
}
}

// Get existing tax queries
$existing_tax_query = (array) $q->get('tax_query');

// Merge existing and new tax queries
$q->set('tax_query', array_merge($existing_tax_query, $tax_query));
}
}
}


Подробнее здесь: https://stackoverflow.com/questions/785 ... oocommerce
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Php»