简体   繁体   中英

WooCommerce how to display products from specific product categories

In my project, restaurants are woocommerce categories, the food combos they deliver are products. At the web appliance, the first input of the customer is the delivery address, then in the second page only the restaurants able to deliver there should be displayed.

In the wp_mysql db I created a dedicated table where each restaurant has its own address and delivery range. With the help of google maps API and a custom query I easily manage to get the list of restaurants can deliver at the customer specified address (more precisely I get the list of category_IDs).

The question is: How can I display products from this selected WooCommerce product category term Ids (so the restaurants)?

Is it feasible at all within WooCommerce?

The following code will alter the product query, based on an array of product category term Ids (so you will have to include inside this function, the code to get those product category term Ids) :

add_filter( 'woocommerce_product_query_tax_query', 'only_specific_product_category_terms', 10, 2 );
function only_specific_product_category_terms( $tax_query, $query ) {
    if( ! is_admin() ) {
        $term_ids = array( 11, 13, 14, 15 ); // <== Here you will set your product category term ids
    
        $tax_query[] = array(
            'taxonomy' => 'product_cat',
            'field'    => 'term_id', // Or 'name' or 'slug'
            'terms'    => $term_ids
        );
    }

    return $tax_query;
}

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

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