Search code examples
phpwordpresswoocommerceproduct

Exclude specific product ID and/or categogry in WooCommerce Dynamic Pricing


The following code is working to exclude products from the Dynamic Pricing discount if they are on sale. Now I would like to extend this function to also include specific products and categories (not necessarily in the same function).

Is it sufficient with the ID to add to the if-statement a "or product id = xx" ?

Here's the code so far:

add_filter( 'woocommerce_dynamic_pricing_process_product_discounts', 'is_product_eligible', 10, 4 );

function is_product_eligible( $eligible, $product, $discounter_name, $discounter_object ) {
    remove_filter( 'woocommerce_dynamic_pricing_process_product_discounts', 'is_product_eligible', 10, 4 );

    if ( $product->get_sale_price() ) {
        $eligible = false;
    }

    add_filter( 'woocommerce_dynamic_pricing_process_product_discounts', 'is_product_eligible', 10, 4 );

    return $eligible;
}

Solution

  • You can try the following that will handle specific product ids and product categories to be defined in the code (Untested):

    add_filter( 'woocommerce_dynamic_pricing_process_product_discounts', 'is_product_eligible', 10, 4 );
    function is_product_eligible( $eligible, $product, $discounter_name, $discounter_object ) {
        // Here Define product ids to be excluded
        $product_ids = array( 37, 53 );
    
        // Here Define product categories to be excluded
        $categories = array( 't-shirts', 'posters' );
    
        remove_filter( 'woocommerce_dynamic_pricing_process_product_discounts', 'is_product_eligible', 10, 4 );
    
        if ( $product->get_sale_price() ) {
            $eligible = false;
        }
    
        // Handling specific product IDS
        if ( in_array( $product->get_id(), $product_ids ) ) {
            $eligible = false;
        }
    
        // Handling specific product categories
        $product_id = $product->get_parent_id() > 0 ? $product->get_parent_id() : $product->get_id();
        if ( has_term( $categories, 'product_cat', $product_id ) ) {
            $eligible = false;
        }
    
        add_filter( 'woocommerce_dynamic_pricing_process_product_discounts', 'is_product_eligible', 10, 4 );
    
        return $eligible;
    }
    

    Code goes in function.php file of your active child theme (or active theme). It should work.