Я пытаюсь создать фильтр для продуктов в 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
Почему в Woocommerce не работает фильтр по категориям? ⇐ Php
Кемеровские программисты php общаются здесь
-
Anonymous
1721885163
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));
}
}
}
Подробнее здесь: [url]https://stackoverflow.com/questions/78559428/why-doesnt-filter-work-in-categories-in-woocommerce[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия