Related Products query category and attribute

I want woocommerce to display related products that match a category as well as an attribute. When I look at the get_related function, I am not sure how to add to the query that pa_city must match a variable $city. I have tried this hook, but it still only matches on category, the city is not being used in the query, no idea why:

add_filter( 'woocommerce_product_related_posts',
           'relate_city' );
function relate_city() {
    $city = isset( $_COOKIE['newcity'] ) ? $_COOKIE['newcity'] : 'not set';
    $get_related_products_args = array(
     'orderby' => 'rand',
     'posts_per_page' => $limit,
     'post_type' => 'product',
     'fields' => 'ids',
     'meta_query' => $meta_query,
     'tax_query' => array(
       'relation' => 'AND',
       array(
         'taxonomy' => 'product_cat',
         'field' => 'id',
         'terms' => $cats_array
       ),
       array(
         'taxonomy' => 'pa_city',
         'field' => 'slug',
         'terms' => array ($city)
       )
     )
    );
    return $get_related_products_args;
}

Any help would be greatly appreciated!

Related posts

Leave a Reply

1 comment

  1. Try This

    add_filter( 'woocommerce_product_related_posts', 
                    'relate_city' );
        function relate_city() {
        $city = isset( $_COOKIE['newcity'] ) ? $_COOKIE['newcity'] : 'not set';
                $get_related_products_args = array(
                    'orderby' => 'rand',
                    'posts_per_page' => $limit,
                    'post_type' => 'product',
                    'fields' => 'ids',
                    'meta_query' => $meta_query,
                    'tax_query' => array(
                        'relation' => 'AND',
                        array(
                            'taxonomy' => 'product_cat',
                            'field' => 'id',
                            'terms' => $cats_array
                        ),
                    array(
                    'key' => 'pa_city',
                    'value' => $city,
                     'compare' => '='
                       )
                    )
                );
                return $get_related_products_args;
        }