How to add a custom fee to a WooCommerce product by product ID.

If you want to add a fixed custom fee to a specific WooCommerce product, you can do so with the help of a simple PHP snippet. In this blog post, we will go over how to implement this code and explain each step in detail.

Step 1: Add the PHP Snippet

The first step is to add the PHP snippet to your WooCommerce website. You can do this by opening your theme’s functions.php file and pasting the code at the bottom of the file. Alternatively, you can use a plugin like Code Snippets to add the code without modifying your theme files.

// Add a fixed custom fee to a specific WooCommerce product. 
// This example adds a $5.00 fee to the product with ID 1234.
function add_custom_fee_to_product( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
        return;

    // Check if product is in the cart
    if ( is_object( WC()->cart ) ) {
        foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
            $_product = $values['data'];
            if ( $_product->get_id() == 1234 ) {
                WC()->cart->add_fee( 'Custom Fee', 5.00 );
            }
        }
    }
}
add_action( 'woocommerce_before_calculate_totals', 'add_custom_fee_to_product', 10, 1 );
 

Step 2: Customize the Code

Next, you’ll need to customize the code to fit your needs. In this example, we are adding a $5.00 fee to the product with ID 1234. If you want to add a different fee or apply it to a different product, you’ll need to modify the code accordingly.

Step 3: Save and Test

Once you have customized the code, save the changes and test it on your website. Add the product with the custom fee to your cart and check that the fee has been added correctly.

How It Works

Let’s take a closer look at how this code works.

The function add_custom_fee_to_product() is triggered before the cart totals are calculated. The code checks if the product with ID 1234 is in the cart and adds a custom fee of $5.00 if it is.

The code uses the WC()->cart object to access the cart items and their properties. The foreach loop iterates over each cart item and checks if the product ID matches 1234. If it does, the add_fee() method is called to add the custom fee.

The add_fee() method takes two arguments: the name of the fee and the amount. In this case, we’re using ‘Custom Fee’ as the name and $5.00 as the amount.

Conclusion

Adding a fixed custom fee to a WooCommerce product is a straightforward process with the help of a simple PHP snippet. By following the steps outlined in this blog post, you can customize the code to fit your needs and add a custom fee to your products. This is a great way to offer additional services or cover extra costs associated with certain products.

Leave a Reply

Your email address will not be published. Required fields are marked *

Con Schneider