Woocommerce categories

Discussion in 'WordPress' started by stephan2307, Nov 5, 2018.

  1. #1
    So I got a site that run woocommerce. On the left had side it has a list of categories.

    At the moment it lists all categories and also shows the count.

    I want to only display categories that have products with a certain meta_value.

    Any ideas how I can do that?

    Thanks.
     
    stephan2307, Nov 5, 2018 IP
  2. MilesWeb

    MilesWeb Well-Known Member

    Messages:
    869
    Likes Received:
    35
    Best Answers:
    7
    Trophy Points:
    173
    #2
    To make sure that you are in the product archive page, pre_get_posts action needs to be used before the loop and conditional)_tags. Also to filter the product categories a taxonomy query will be needed.
    Place the following code in your plugin or theme's function.php file:

    add_action('pre_get_posts','shop_filter_cat');
    
    function shop_filter_cat($query) {
        if (!is_admin() && is_post_type_archive( 'product' ) && $query->is_main_query()) {
           $query->set('tax_query', array(
                        array ('taxonomy' => 'product_cat',
                                           'field' => 'slug',
                                            'terms' => 'type-1'
                                     )
                         )
           );  
        }
    }
    Code (markup):
     
    MilesWeb, Nov 6, 2018 IP