Created
September 30, 2024 07:08
-
-
Save braddalton/d858a95207cd6151d5aba384ff445c08 to your computer and use it in GitHub Desktop.
WooCommerce Product Addons Code https://wpsites.net/free-tutorials/product-addons-by-percentage-for-woocommerce/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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'] ); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment