Home > Software engineering >  Problem with filter woocommerce, filter by tags, not in and taxonomy
Problem with filter woocommerce, filter by tags, not in and taxonomy

Time:11-30

I'm trying to make a query where I enter the codes of the products that I already have on the page, the code of the tag that I am interested in filtering and the taxonomy, but the problem is that it throws me out the products that are filtered by taxonomy but not by tag, or better the tags are wrong, in your opinion what could be the problem?

$terms = get_term_by('name', $_GET['category'], 'product_cat');
            $args = array(
                'post_type' => 'product',
                'post_status' => 'publish',
                'post__not_in' => $_GET['products'],
                'posts_per_page' => $_GET['n_products'],
                'orderby' => 'rand',
                'tag__in' => $_GET['tag_ids'],
                'tax_query' => array(
                    array(
                        'taxonomy' => 'product_cat',
                        'field'    => 'term_id',
                        'terms'     =>  $terms->term_id,
                        'compare' => '=',
                    ),
                )
            );
            $query = new WP_Query($args);

CodePudding user response:

Try to change.

'taxonomy' => 'product_cat', 

to

'taxonomy' => 'product_tag',

Try the below code.

$terms = get_term_by('name', $_GET['category'], 'product_cat');
$product_tag = get_term_by('name', $_GET['category'], 'product_tag');

$args = array(
    'post_type' => 'product',
    'post_status' => 'publish',
    'post__not_in' => $_GET['products'],
    'posts_per_page' => $_GET['n_products'],
    'orderby' => 'rand',
    'tag__in' => $_GET['tag_ids'],
    'tax_query' => array(
        array(
            'taxonomy' => 'product_cat',
            'field'    => 'term_id',
            'terms'     =>  $terms->term_id,
            'compare' => '=',
        ),
         array(
            'taxonomy' => 'product_tag',
            'field'    => 'term_id',
            'terms'     =>  $product_tag->term_id,
            'compare' => '=',
        ),
    )
);
$query = new WP_Query($args);
  • Related