0

I found the code below to display variable products in the shop. After a small modification it works fine. But it also displays the variations in all categories, instead of only showing the variations of the current category.

add_action( 'pre_get_posts', 'custom_modify_query_get_posts_by_date' );

// Modify the current query

function custom_modify_query_get_posts_by_date( $query ) {
 if ( ! is_admin() && $query->is_main_query() ) {

    if ( is_post_type_archive( 'product' ) || is_product_category() || is_product_tag() ) {
       $query->set( 'order', 'ASC' );
           add_filter( 'posts_where', 'rc_filter_where' );
   }
     return $query;
 }
}

// Add products variation post type to the loop
function rc_filter_where( $where = '' ) {

   $type = 'product_variation';
   $where .= " OR post_type = '$type'";

   return $where;

}

I figured if I can limit the pre_get_posts to the current category that should work. Tried a lot of things, but I can't get it to work.

add_action( 'pre_get_posts', 'custom_modify_query_get_posts_by_date' );

// Modify the current query

function custom_modify_query_get_posts_by_date( $query ) {
 if ( ! is_admin() && $query->is_main_query() ) {

 if ( is_product_category() ) {
    $cate = get_queried_object();
    $cateID = $cate->term_id;

       $query->set( 'order', 'ASC' );
       $query->set('cat', $cateID);
           add_filter( 'posts_where', 'rc_filter_where' );
   } elseif ( is_post_type_archive( 'product' ) || is_product_tag() ) {
       $query->set( 'order', 'ASC' );
           add_filter( 'posts_where', 'rc_filter_where' );
   }
     return $query;
 }
}

// Add products variation post type to the loop
function rc_filter_where( $where = '' ) {

   $type = 'product_variation';
   $where .= " OR post_type = '$type'";

   return $where;
}

So I would like to know if it's possible to show all product variations in the shop and on the category view only show the variations that belong to that category.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.