Site icon Hip-Hop Website Design and Development

WooCommerce add extra price to products by each category

i want to do: add extra price to category based products

Problem: The code below does not work for products with variations.

add_filter('woocommerce_get_price', 'woocommerce_change_price_by_addition', 10, 2);

// here is the problem
add_filter( 'woocommerce_variable_sale_price_html', 'woocommerce_change_price_by_addition', 10, 2 );
add_filter( 'woocommerce_variable_price_html', 'woocommerce_change_price_by_addition', 10, 2 );
// here is the problem - end

function woocommerce_change_price_by_addition($price, $product) {
    // Product ID
    $product_id = isset($product->id) ? $product->id : 0;
    $product_categories_id = isset($product->category_ids) ? $product->category_ids : array();

    $extra_amount = 0;
    if(!empty($product_categories_id))
    {
        foreach($product_categories_id as $cat_id)
        {
            $category_extra_price = (float)get_term_meta($cat_id, 'extra_price', true);

            if ($category_extra_price && is_numeric($category_extra_price)) 
            {
                $extra_amount = $extra_amount + $category_extra_price;
            }
        }
    }
    if ($product_id) {
        //get the product
        $product = wc_get_product($product_id);
    
        // change the price by adding the 35
        $price = ($price + $extra_amount);
        
        //return the new price
        return  $price;
    }
}

I got the above code from this link https://stackoverflow.com/a/69625481/12118468

variation selection