Cant loop throught WP_Query() in Woocomerce

I want to filter my WooCommerce products on the archive page with Ajax, but when i send the wp_query to the functions it wont loop through the posts. When i var_dump($posts); it show the data but when is use $posts->have_posts() it doesnt do anything.

functions.php // include data in Ajax

wp_enqueue_script( 'ajax-filter', THEME_DIR.'/assets/js/ajax-filter.js' );
global $wp_query;
wp_localize_script( 'ajax-filter', 'ajaxfilter', array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'query_vars' => json_encode( $wp_query )));


        url: ajaxfilter.ajaxurl,
        type: 'post',
        data: {
            action: 'ajax_filter',
            query_vars: ajaxfilter.query_vars
        beforeSend: function() {
        success: function( html ) {
            $('.products').append( html );


function my_ajax_filter() {
$query_vars = json_decode( stripslashes( $_POST['query_vars'] ), true );

$posts = new WP_Query( $query_vars );
$GLOBALS['wp_query'] = $posts;

$products = $posts->query['posts'];

    echo '<h1>Test text</h1>';

Read more here: Cant loop throught WP_Query() in Woocomerce

Leave a Reply

Your email address will not be published. Required fields are marked *