Reputation: 25
I would like to add a dropdown menu where the visitor can choose between 12 months, and based on that choice, the price per month is shown in installments.
Lets say i have a product with price 120 usd. A banner will inform the customer:
"you can purchase the item in installemets, select the the number"
The customer will select for example 3 months and in the banner below the dropdown the result will be 40 usd /month
Currently my code only works for 12 months.
add_action( 'woocommerce_after_add_to_cart_button', 'show_installments', 20 );
function show_installments() {
global $product;
$id = $product->get_id();
$product = wc_get_product( $id );
$a = $product->get_price();
$b = 12;
$min = 25;
$c = round( $a / $b, 2);
if ($a > $min) {
echo '<p class="p2_installments_12months">Purchase with'.$c.'€ per month for 12 months </p>';
}
}
Upvotes: 1
Views: 247
Reputation: 29650
You can use the following code, note that jQuery
is also needed for the interaction between the dropdown and the editing of the text
function show_installments() {
global $product;
// Get product id
$product_id = $product->get_id();
// Get price
$price = $product->get_price();
// Set min price
$min_price = 25;
if ( $price > $min_price ) {
echo '<div class="my_select_box">';
woocommerce_form_field( 'month_options', array(
'type' => 'select',
'label' => __('You can purchase the item in installemets, select the the number'),
'required' => false,
'return' => false,
'options' => array(
'' => 'Select...',
'1' => '1 month',
'2' => '2 months',
'3' => '3 months',
'4' => '4 months',
'5' => '5 months',
'6' => '6 months',
'7' => '7 months',
'8' => '8 months',
'9' => '9 months',
'10' => '10 months',
'11' => '11 months',
'12' => '12 months',
)
), '' );
echo '</div>';
echo '<div class="p2_installments_12months"></div>';
?>
<script type="text/javascript">
jQuery(document).ready(function ($) {
var product_price = <?php echo $product->get_price(); ?>;
$( '[name=month_options]' ).change(function() {
var dropdown_val = this.value;
if ( dropdown_val >= 1 ) {
var price_per_month = ( product_price / dropdown_val ).toFixed(2);
$( '.p2_installments_12months' ).html( '<p class="p2_installments_12months">Purchase with ' + price_per_month + ' € per month for 12 months </p>' );
} else {
$( '.p2_installments_12months' ).html( '<p class="p2_installments_12months"></p>' );
}
});
});
</script>
<?php
}
}
add_action( 'woocommerce_after_add_to_cart_button', 'show_installments', 20 );
Upvotes: 1