简体   繁体   中英

Exclude downloadable products from shop pages in Woocommerce

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!

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…

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM