skip to Main Content

Im trying to make ajax filter by attributes for woocommerce.
The problem is query giving empty result, when I’m adding tax_query. This code goes 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’ve checked the database for pa_chrisi taxonomy.
I’ve tried:

  • to init woocommerce (not sure why) before my code.
  • to add 'suppress_filters' => true, and 'include_children' => false,

echo $newquery->request; gives me

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 I remove tax_query part it works well. Im getting all products.

Please help me!

2

Answers


  1. Chosen as BEST ANSWER

    solution: if you are using WP_Query with tax_query in functions.php put the code inside an 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
    }
    

  2. As alternative you can register WC taxonomies before query via:

    WC_Post_Types::register_taxonomies();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search