This code enables you to include addons on single products for anything like warranty, premium support or any type of upgrade.
Once your customer selects the addon, the single product price is updated to include the price of the addon.
In this case, the addon price is a percentage of the single product price.
The addon percentage applies per item quantity and is included on the :
- Cart Page
- Checkout page
- Order Received page
- Admins WooCommerce orders item data
Code Installation
Copy and paste to your child themes functions file or custom functionality/code snippets plugin.
add_action( 'woocommerce_before_add_to_cart_button', 'custom_product_addons', 10 );
function custom_product_addons() {
global $product;
$product_price = $product->get_price(); // Base price of the product.
?>
<div id="product-warranty-addons">
<p>Select Additional Warranty:</p>
<button type="button" class="warranty-addon" data-addon="15" data-price="<?php echo esc_attr( $product_price ); ?>">
Additional 4-Month Warranty (+15%)
</button>
<button type="button" class="warranty-addon" data-addon="30" data-price="<?php echo esc_attr( $product_price ); ?>">
Additional 8-Month Warranty (+30%)
</button>
</div>
<input type="hidden" id="addon_price_value" name="addon_price_value" value="0">
<?php
}
add_action( 'wp_footer', 'custom_product_addons_script' );
function custom_product_addons_script() {
if ( is_product() ) { ?>
<script type="text/javascript">
jQuery(document).ready(function($) {
$('.warranty-addon').on('click', function() {
var addonPercentage = $(this).data('addon');
var basePrice = parseFloat($(this).data('price'));
var addonPrice = (addonPercentage / 100) * basePrice;
var totalPrice = basePrice + addonPrice;
// Update price display on the product page
$('.woocommerce-Price-amount').text('€' + totalPrice.toFixed(2));
// Set hidden input value for addon price
$('#addon_price_value').val(addonPrice.toFixed(2));
});
});
</script>
<?php }
}
add_filter( 'woocommerce_add_cart_item_data', 'custom_add_cart_item_data', 10, 2 );
function custom_add_cart_item_data( $cart_item_data, $product_id ) {
if( isset( $_POST['addon_price_value'] ) ) {
$cart_item_data['addon_price'] = sanitize_text_field( $_POST['addon_price_value'] );
$cart_item_data['unique_key'] = md5( microtime().rand() ); // To avoid merging of items
}
return $cart_item_data;
}
add_action( 'woocommerce_before_calculate_totals', 'custom_addon_price_to_cart' );
function custom_addon_price_to_cart( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) ) {
return;
}
// Adjust the product price
foreach ( $cart->get_cart() as $cart_item ) {
if( isset( $cart_item['addon_price'] ) ) {
$cart_item['data']->set_price( $cart_item['data']->get_price() + $cart_item['addon_price'] );
}
}
}
Extend Addons
The WC Percentage Addons Per Product plugin extends this code further to :
- Include repeater fields per product enabling unique addons per product.
Was This Tutorial Helpful?