Exclude downloadable products from shop pages in W

2019-07-31 03:53发布

I'm developing a Woocommerce shop with both physical and downloadable products. I would like to alter the standard query for the loop to exclude all downloadable products, but I can't figure out a way to do it. I would like these products to only be displayed on a certain archive page, which is no problem to achieve.

I'm doing a few other alterations of the query using pre_get_post, but I can't seem to find an option for downloadable products.

All my products are simple products.

Any help would be greatly appreciated!

1条回答
倾城 Initia
2楼-- · 2019-07-31 04:20

Instead of using pre_get_post, you could use the dedicated woocommerce_product_query Woocommerce action hook. But as downloadable products are related to a meta query is better to use woocommerce_product_query_meta_query Woocommerce dedicated filter hook.

It will remove downloadable products from shop page only:

add_filter( 'woocommerce_product_query_meta_query', 'downloadable_not_in_shop', 20, 2 );
function downloadable_not_in_shop( $meta_query, $query ) {
    // Only on archive pages
    if( is_admin() || ! is_shop() )
        return $meta_query; // exit

    $meta_query[] = array(
        'key'     => '_downloadable',
        'value'   => 'yes',
        'compare' => '!=',
    );

    return $meta_query;
}

Code goes in function.php file of your active child theme (or theme). Tested and works.

To display only downloadable products you will use 'compare' => '=', instead…

查看更多
登录 后发表回答