A
A
agletd2021-07-20 12:05:49
WordPress
agletd, 2021-07-20 12:05:49

How to get products with given woocommerce attribute?

Hey! I finish the filter of goods by attributes. After selecting the first attribute in the form, you need to get a list of products with this attribute. But the query returns an empty result when I add tax_query . The code is in functions.php

$newquery = new WP_Query( array(
        'post_type'             => 'product',
           'posts_per_page'        => '22',
           'post_status' => 'publish',
           'tax_query' => array( array(
               'taxonomy' => 'pa_chrisi', // Product attribute taxonomy: always start with 'pa_'
               'field'    => 'term_id', // Can be 'term_id', 'slug' or 'name'
               'terms'    => 170,
           ), ),
    
    ) );


I checked the db against taxonomy pa_chrisi . I tried
- do init woocommerce (although I didn't quite understand why) before my code.
- added to the request 'suppress_filters' => true, and 'include_children' => false,

echo $newquery->request; outputs:
SELECT SQL_CALC_FOUND_ROWS dmg0j_posts.ID FROM dmg0j_posts WHERE 1=1 AND ( 0 = 1 ) AND dmg0j_posts.post_type = 'product' AND ((dmg0j_posts.post_status = 'publish')) GROUP BY dmg0j_posts.ID ORDER BY dmg0j_posts.post_date DESC LIMIT 0, 22


If you remove tax_query, then everything works, all products are displayed.
Is there any way to get around the problem? In general, the logic is: in the 3 select-a form, select the first attribute - in the second, we display only those attribute options that are available for products containing the 1st attribute. If you do not carry out this check and let you select any attribute in all three selects, then in 90% of cases the search will give nothing and the person will leave.

Help colleagues! The first time I write)) Usually I google everything myself. I broke my head, I can't sleep, I can't eat!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
agletd, 2021-07-31
@agletd

I found the answer myself.
If you are using WP_Query with tax_query in functions.php put your code in add_action with low priority:

add_action( 'init', 'maratgenius', 999 );
function maratgenius()
{
            $newquery = new WP_Query( array(
                'post_type'             => 'product',
                   'posts_per_page'        => '-1',
                   'post_status' => 'publish',
                   'tax_query' => array( array(
                       'taxonomy' => 'pa_chrisi', // Product attribute taxonomy: always start with 'pa_'
                       'field'    => 'term_id', // Can be 'term_id', 'slug' or 'name'
                       'terms'    => $_POST['get_what'],
                   ), ),
            
            ) );
//other code
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question