Press enter to see results or esc to cancel.

Excluding WooCommerce products from categories via the REST API

In short, this code helps exclude products from specific WooCommerce categories when using the REST API. It works by:

  1. Defining the categories you want to exclude based on their slugs.
  2. Fetching the IDs of those categories.
  3. Modifying the REST API query to exclude all products in those categories using the NOT IN operator.
  4. Applying the change using the woocommerce_rest_product_query filter.

This way, products from the specified categories won’t appear in REST API responses, improving customization and control over your WooCommerce store’s data.

function exclude_categories_from_rest_api( $args, $request ) {
    // Define the category slugs you want to exclude
    $excluded_category_slugs = array( 'your-first-category-slug', 'your-second-category-slug' ); // Replace with actual category slugs

    // Get the term IDs for the excluded categories
    $excluded_category_ids = array();
    foreach ( $excluded_category_slugs as $category_slug ) {
        $term = get_term_by( 'slug', $category_slug, 'product_cat' );
        if ( $term && ! is_wp_error( $term ) ) {
            $excluded_category_ids[] = $term->term_id;
        }
    }

    // Check if we have valid category IDs to exclude
    if ( ! empty( $excluded_category_ids ) ) {
        // Modify the tax_query to exclude products from these categories
        $args['tax_query'] = isset( $args['tax_query'] ) ? $args['tax_query'] : array();
        $args['tax_query'][] = array(
            'taxonomy' => 'product_cat',
            'field'    => 'term_id',
            'terms'    => $excluded_category_ids,
            'operator' => 'NOT IN',
        );
    }

    return $args;
}

add_filter( 'woocommerce_rest_product_query', 'exclude_categories_from_rest_api', 10, 2 );