Hide / show conditional field on checkout based on payment option - woocommerce

I have four different payment options on checkout. When choosing Credit card and PayPal I have 4 filds: email, first name, last name and phone number. When choosing BACS or COD option for payment I want to show additional fields: billing_address_1, billing_city_1, billing_postcode and billing_country.
I managed to do that with a snippet below, but only for BACS or COD, not both... I tried making two snippets, one for each with different value in payment_method.
class TEMP_WFACP_Conditional_Field_Depend_On_Payment {
private $conditional_field = [];
private $exclude_wfacp_ids = [];
public function __construct() {
$this->conditional_field = [
'payment_method' => [
[
'value' => 'bacs',
'fields' => [ 'billing_address_1', 'billing_city' , 'billing_postcode' , 'billing_country' ],
'enable' => true,
]
]
];
add_action( 'wfacp_after_checkout_page_found', [ $this, 'wfacp_add_script' ] );
add_filter( 'woocommerce_checkout_fields', [ $this, 'wfacp_remove_required' ], 9, 1 );
}
function wfacp_add_script() {
if ( in_array( WFACP_Common::get_id(), $this->exclude_wfacp_ids ) ) {
return;
}
add_action( 'wp_footer', [ $this, 'wfacp_conditional_field_script' ] );
}
function wfacp_conditional_field_script() {
$fields = json_encode( $this->conditional_field );
$fields_trr = json_encode( $this->conditional_field_trr );
?>
<style>
#billing_country_field b {
display: none !important;
}
p.conditional_field {
display: none !important;
}
.wfacp_dropdown option, .wfacp_dropdown select {
text-transform: capitalize;
}
</style>
<script>
jQuery(document).ready(function ($) {
var conditional_fields =<?php echo $fields;?>;
conditionField();
function conditionField() {
$.each(conditional_fields, function (field, values) {
$.each(values, function (key, value) {
var payment_method = $("input[name=payment_method]:checked" ).val();
var field = 'payment_method_'+payment_method;
displayConditionalField(field, value, payment_method);
$(document.body).on('change', '.wc_payment_method .input-radio' , function () {
var id = $(this).attr('id');
var val = $(this).val();
displayConditionalField(id, value, val);
});
});
});
}
function displayConditionalField(id, values, val) {
$.each(values.fields, function (index, field) {
var show = false;
if (val === 'null') {
val = $('#' + id ).val();
}
// console.log(field,val,values.value,values.enable);
if (val === values.value) {
show = true;
}
// console.log(val,field,country);
if (show && values.enable) {
$('#' + field + '_field').removeClass('conditional_field');
} else {
$('#' + field + '_field').addClass('conditional_field');
}
});
}
jQuery(function(){
jQuery( 'body' )
.on( 'updated_checkout', function() {
usingGateway();
jQuery('input[name="payment_method"]').change(function(){
console.log("payment method changed");
usingGateway();
});
});
});
function usingGateway(){
console.log(jQuery("input[name='payment_method']:checked").val());
if(jQuery('form[name="checkout"] input[name="payment_method"]:checked').val() == 'bacs'){
$("html, body").animate({
scrollTop: 0
}, 600);
$('#div_block-100-52320').css("display","flex");
}
else{
$('#div_block-100-52320').css("display","none");
}
}
});
</script>
<?php
}
function wfacp_remove_required( $fields ) {
if ( ! class_exists( 'WFACP_Common' ) && in_array( WFACP_Common::get_id(), $this->exclude_wfacp_ids ) ) {
return $fields;
}
foreach ( $this->conditional_field as $field => $conditional_fields ) {
foreach ( $conditional_fields as $conditional_field ) {
if ( ! isset( $_REQUEST[ $field ] ) || false == $conditional_field['enable'] || $_REQUEST[ $field ] == $conditional_field['value'] ) {
if ( 'bacs' === $conditional_field['value'] ) {
continue;
}
}
foreach ( $conditional_field['fields'] as $field_id ) {
$section = '';
if ( isset( $fields['billing'][ $field_id ] ) ) {
$section = 'billing';
} elseif ( isset( $fields['shipping'][ $field_id ] ) ) {
$section = 'shipping';
} elseif ( isset( $fields['advanced'][ $field_id ] ) ) {
$section = 'advanced';
}
if ( ! empty( $section ) ) {
unset( $fields[ $section ][ $field_id ]['required'] );
}
}
}
}
return $fields;
}
function wfacp_remove_field( $fields ) {
if ( in_array( WFACP_Common::get_id(), $this->exclude_wfacp_ids ) ) {
return $fields;
}
$user_id = get_current_user_id();
foreach ( $this->conditional_field as $field => $conditional_fields ) {
foreach ( $conditional_fields as $conditional_field ) {
if ( ! isset( $_REQUEST[ $field ] ) || ( false == $conditional_field['enable'] || $_REQUEST[ $field ] == $conditional_field['value'] ) ) {
continue;
}
foreach ( $conditional_field['fields'] as $field_id ) {
if ( ! empty( $fields['advanced'][ $field_id ] ) ) {
unset( $fields['advanced'][ $field_id ] );
}
$fields['advanced'][ $field_id ]['value']=get_user_meta($user_id,$field,true);
}
}
$fields['advanced'][ $field ]['value']=get_user_meta($user_id,$field,true);
}
return $fields;
}new TEMP_WFACP_Conditional_Field_Depend_On_Payment();

Related

Unable to select shipping method after filtering 'woocommerce_package_rates'

I just wrote this filter to disable non-free shipping methods when free shipping is available:
add_filter( 'woocommerce_package_rates', 'disable_paid_shipping', 9999, 2 );
function disable_paid_shipping( $rates, $package ) {
$free_rates = array();
foreach ( $rates as $i => $rate ) {
if ( str_contains( $rate->label, "gratuita" ) OR str_contains( $rate->label, "gratuito" ) ) {
$free_rates[] = $rate;
}
if ( str_contains( $rate->id, "local") ) {
$local = $rate;
}
if ( str_contains( $rate->id, "fermopoint") ) {
$fermopoint = $rate;
}
}
if ( !empty( $free_rates ) ) {
if ( isset($fermopoint) ) {
$fermopoint->cost = 0;
$fermopoint->label .= ' gratuito';
array_unshift( $free_rates, $fermopoint );
}
if ( isset($local) ) {
$free_rates[] = $local;
}
$rates = $free_rates;
}
return $rates;
}
The code works as expected, unless for two unexpected events occurring:
no shipping method is selected by default anymore (both in cart and checkout page)
when I choose one in the cart page, it gets unselected right after (only in cart page)
To solve the 1st problem at checkout, I can work around by forcing the selection through a hook on woocommerce_before_cart (although this looks like a forced trick).
For the 2nd problem I have no idea.
Suggestions?
The problem lies in that the WC $rates array is an associative array:
$rates = Array (
[rate_id_0] => [rate_obj_0]
[rate_id_1] => [rate_obj_1]
...
);
While the newly created $free_rates is an indexed array:
$free_rates = Array (
[0] => [rate_obj_0]
[1] => [rate_obj_1]
...
);
As result, WC is unable to match the new $free_rates array with the user's default rate_id, which is supposed to be used as the array key.
Here's the working code:
add_filter( 'woocommerce_package_rates', 'disable_paid_shipping', 9999, 2 );
function disable_paid_shipping( $rates, $package ) {
$free_rates = array();
foreach ( $rates as $i => $rate ) {
if ( str_contains( $rate->label, "gratuita" ) OR str_contains( $rate->label, "gratuito" ) ) {
$free_rates[$rate->id] = $rate;
}
if ( str_contains( $rate->id, "local") ) {
$local = $rate;
}
if ( str_contains( $rate->id, "fermopoint") ) {
$fermopoint = $rate;
}
}
if ( !empty( $free_rates ) ) {
if ( isset($fermopoint) ) {
$fermopoint->cost = 0;
$fermopoint->label .= ' gratuito';
$free_rates = array($fermopoint->id => $fermopoint) + $free_rates; // to set it as 1st
}
if ( isset($local) ) {
$free_rates[$local->id] = $local;
}
$rates = $free_rates;
}
return $rates;
}

WooCommerce Hide Payment Gateway for Custom Attribute

Just starting in my WordPress/WooCommerce journey.
I found a question on here from a while back asking about restricting payment gateways for a specific attribute selection. I've tried to integrate this into my site and I cannot get it working! I've added the Attribute and Terms, and the slugs are as follows - pay_now_deposit (attr) and pay_now / deposit (terms).
I'm looking to restrict Klarna payments for those paying by deposit, and the code I have is below -
function conditional_payment_gateways( $available_gateways ) {
$in_cart = false;
foreach ( WC()->cart->get_cart_contents() as $key => $values ) {
// See if there is an attribute called 'pa_size' in the cart
// Replace with whatever attribute you want
if (array_key_exists('pa_pay_now_deposit', (array) $values['data']->get_attributes() ) ) {
foreach ($values['data']->get_attributes() as $attribute => $variation);
// Replace 'small' with your value.
if ($variation == 'deposit') $in_cart = true; //edited
}
}
if ( $in_cart ) {
unset($available_gateways['klarna_payments']);
}
else {
unset($available_gateways['cod']);
}
return $available_gateways;
}
Any advice on where I'm going wrong would be greatly appreciated!
Try to add a break statement.
add_filter('woocommerce_available_payment_gateways', 'conditional_payment_gateways', 10, 1);
function conditional_payment_gateways( $available_gateways ) {
$in_cart = false;
foreach ( WC()->cart->get_cart_contents() as $key => $values ) {
if ( array_key_exists( 'pa_pay_now_deposit', (array) $values['data']->get_attributes() ) ) {
foreach ( $values['data']->get_attributes() as $attribute => $variation ){
if ( $variation == 'deposit' ){
$in_cart = true; //edited
break;
}
}
}
if( $in_cart ){
break;
}
}
if ( $in_cart ) {
unset( $available_gateways['klarna_payments'] );
}else {
unset( $available_gateways['cod'] );
}
return $available_gateways;
}

How to rename the Add to Cart button if the product is already added to cart in WooCommerce

When Ajax add to cart functionality is active on my WooCommerce store, on Ajax add to cart first click It shows a checked icon symbol like:
The code below changes the add to button cart text to "Seçildi !" if product is already in to cart, only after refreshing page like:
//Rename the button on the Product page
add_filter( 'woocommerce_product_single_add_to_cart_text', 'ts_product_add_cart_button' );
function ts_product_add_cart_button( $label ) {
foreach( WC()->cart->get_cart() as $cart_item_key => $values ) {
$product = $values['data'];
if( get_the_ID() == $product->get_id() ) {
$label = __('Seçildi !', 'woocommerce');
}
}
return $label;
}
//Rename the button on the Shop page
add_filter( 'woocommerce_product_add_to_cart_text', 'ts_shop_add_cart_button', 99, 2 );
function ts_shop_add_cart_button( $label, $product ) {
if ( $product->get_type() == 'simple' && $product->is_purchasable() && $product->is_in_stock() )
{
foreach( WC()->cart->get_cart() as $cart_item_key => $values ) {
$_product = $values['data'];
if( get_the_ID() == $_product->get_id() ) {
$label = __('Seçildi !', 'woocommerce');
}
}
}
return $label;
}
But if you don't refresh the page the button remains like before with the checked icon symbol.
What I would like is to change add to cart button with the quantity that has been added for this product like:
Is this possible? What do I need to change? Any help is appreciated.
You can use WC woocommerce_product_add_to_cart_text action hook and you can get wc cart loop through all products and compare path second params $prodcuct object. check below code. code will go active theme functions.php file.
function change_add_to_cart_text_if_product_already_in_cart( $add_to_cart_text, $product ) {
if ( WC()->cart ) {
$cart = WC()->cart; // Get cart
if ( ! $cart->is_empty() ) {
foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
$_product_id = $cart_item['product_id'];
if ( $product->get_id() == $_product_id ) {
$add_to_cart_text = '('.$cart_item['quantity'].')'.' Already in cart';
break;
}
}
}
}
return $add_to_cart_text;
}
add_filter( 'woocommerce_product_add_to_cart_text', 'change_add_to_cart_text_if_product_already_in_cart', 10, 2 );
add_filter( 'woocommerce_product_single_add_to_cart_text', 'change_add_to_cart_text_if_product_already_in_cart', 10, 2 );
Updated ( as per OP request how to change text quick on click with quantity ).
There is two way You can do this.
you can use woocommerce_loop_add_to_cart_args and add product qty attribute and based on that you can display.
function add_product_qty( $args, $product ){
if ( WC()->cart ) {
$cart = WC()->cart; // Get cart
if ( ! $cart->is_empty() ) {
foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
$_product_id = $cart_item['product_id'];
if ( $product->get_id() == $_product_id ) {
$args['attributes']['data-product-qty'] = $cart_item['quantity'];
}else{
$args['attributes']['data-product-qty'] = 0;
}
}
}else{
$args['attributes']['data-product-qty'] = 0;
}
}
return $args;
}
add_filter( 'woocommerce_loop_add_to_cart_args', 'add_product_qty', 10, 2 );
add_action( 'wp_footer', 'ajax_button_text_quick_change_js_script' );
function ajax_button_text_quick_change_js_script() {
?>
<script>
(function($) {
$(document.body).on('click', '.ajax_add_to_cart', function(event){
$this = $(this);
var product_qty = parseInt($this.attr('data-product-qty')) + 1;
$this.attr('data-product-qty',product_qty);
var buttonText = '<span class="add_to_cart_text product-is-added">('+product_qty+') Already in cart</span><i class="cart-icon pe-7s-cart"></i>';
$this.html(buttonText).attr('data-tip','('+product_qty+') Already in cart');
});
})(jQuery);
</script>
<?php
}
You can use added_to_cart jQuery event that triggers after adding to the cart you call ajax and get add_to_cart_text in response.
add_action( 'wp_footer', 'ajax_button_text_js_script' );
function ajax_button_text_js_script() {
?>
<script>
(function($) {
$(document.body).on('added_to_cart', function(event, fragments, cart_hash, button){
var product_id = button.data('product_id'),
product_qty = button.data('quantity');
button.addClass('loading');
$.ajax({
url: "<?php //echo admin_url('admin-ajax.php'); ?>",
method: 'POST',
data:{action:'change_add_to_cart_text',product_id:product_id},
dataType: "json",
success: function( response ){
var buttonText = '<span class="add_to_cart_text product-is-added">'+response.data.button_text+'</span><i class="cart-icon pe-7s-cart"></i>';
button.html(buttonText).attr('data-tip',response.data.button_text);
button.removeClass('loading');
},error: function (jqXHR, exception) {
var msg = '';
if (jqXHR.status === 0) {
msg = 'Not connect.\n Verify Network.';
} else if (jqXHR.status == 404) {
msg = 'Requested page not found. [404]';
} else if (jqXHR.status == 500) {
msg = 'Internal Server Error [500].';
} else if (exception === 'parsererror') {
msg = 'Requested JSON parse failed.';
} else if (exception === 'timeout') {
msg = 'Time out error.';
} else if (exception === 'abort') {
msg = 'Ajax request aborted.';
} else {
msg = 'Uncaught Error.\n' + jqXHR.responseText;
}
console.log(msg);
},
});
});
})(jQuery);
</script>
<?php
}
add_action('wp_ajax_change_add_to_cart_text', 'change_add_to_cart_text');
add_action('wp_ajax_nopriv_change_add_to_cart_text', 'change_add_to_cart_text');
function change_add_to_cart_text(){
$product_id = $_POST['product_id'];
if ( WC()->cart ) {
$cart = WC()->cart; // Get cart
if ( ! $cart->is_empty() ) {
foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
$_product_id = $cart_item['product_id'];
if ( $product_id == $_product_id ) {
$add_to_cart_text = '('.$cart_item['quantity'].')'.' Already in cart';
break;
}
}
}
}
wp_send_json_success(array(
'button_text' => $add_to_cart_text
));
}
This below code only for OP site.
add_filter( 'woocommerce_loop_add_to_cart_link', 'custom_add_quantity_fields', 99, 2 );
function custom_add_quantity_fields($html, $product) {
//add quantity field only to simple products
if ( $product && $product->is_type( 'simple' ) && $product->is_purchasable() && $product->is_in_stock() && ! $product->is_sold_individually() ) {
if ( WC()->cart ) {
$cart = WC()->cart; // Get cart
if ( ! $cart->is_empty() ) {
foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
$_product_id = $cart_item['product_id'];
if ( $product->get_id() == $_product_id ) {
$data_product_qty = $cart_item['quantity'];
}else{
$data_product_qty = 0;
}
}
}else{
$data_product_qty = 0;
}
}
//rewrite form code for add to cart button
$html = '<form action="' . esc_url( $product->add_to_cart_url() ) . '" class="cart" method="post" enctype="multipart/form-data">';
$html .= woocommerce_quantity_input( array(), $product, false );
$html .= '<button type="submit" data-quantity="1" data-product_id="' . $product->get_id() . '" class="button alt ajax_add_to_cart add_to_cart_button product_type_simple" data-product-qty="'.$data_product_qty.'">' . esc_html( $product->add_to_cart_text() ) . '</button>';
$html .= '</form>';
}
return $html;
}
Tested and works.

how convert simple form submit to ajax submit without loading page like add product to cart function

how convert simple form submit to ajax submit without loading page like add the product to cart function
`
">
">
<button type="submit" name="addift_add_wl_btn_popup">Add to Wishlist</button>
</form>
session
public function addify_get_sectiuon_btn() {
$wl_p_id = '';
if ( isset( $_POST['addift_add_wl_btn_popup'] ) ) {
if ( isset( $_POST['addify_wl_product_id'] ) ) {
$addify_add_to_wl_pro = sanitize_text_field( wp_unslash( $_POST ['addify_wl_product_id'] ) );
}
$addify_wl_var1 = array();
$addify_wl_var1 = WC()->session->get( 'addify_section_name' );
if ( !empty( $addify_wl_var1) ) {
$addify_wl_var2 =$addify_add_to_wl_pro;
array_push( $addify_wl_var1 ,$addify_wl_var2);
WC()->session->set( 'addify_section_name', $addify_wl_var1 );
} else {
WC()->session->set( 'addify_section_name', array($addify_add_to_wl_pro) );
}
// WC()->session->set( 'addify_section_name', null );
}
}
#In jQuery#
listen to form submit and attach this code.
Remember to add event.preventDefault()'
$.post(
ajaxurl,
{ action: 'action_registered_by_add_action', addift_add_wl_btn_popup: addift_add_wl_btn_popup, addify_wl_product_id:addify_wl_product_id },
function( response ) {
//do something
}
);
#In PHP#
//register ajax
add_action( 'wp_ajax_ACTION_NAME', function(){
//base stufs here
} );
```--
###or###
add_action( 'wp_ajax_ACTION_NAME', [$this, 'method'] );
##EDITED##
//add this register to handle both logged in and not logged in users
//add_action( 'wp_ajax_addify_get_sectiuon_btn',array( $this, 'addify_get_sectiuon_btn'));
//add_action( 'wp_ajax_nopriv_addify_get_sectiuon_btn',array( $this, 'addify_get_sectiuon_btn'));
( function ( $ ) {
$( function () {
$( document ).ready( function ( $ ) {
jQuery( '.addift_add_wl_btn_popup_class' ).click( function () {
alert( "ok" );
} );
$( '.addift_add_wl_btn_popup_class' ).click( function ( event ) {
event.preventDefault(); //prevent default behaviour - you have must add function param named `event`
/*
* if its *.js file you must localize script to add variable see more https://wordpress.stackexchange.com/a/190299
* if its *.php file you can do this dirty inline php inside script
*/
let ajaxurl = "<?php echo admin_url( 'admin-ajax.php' ) ?>"; // wp ajax url obtain by wc helper {{ admin_url( 'admin-ajax.php' ) }}
let addift_add_wl_btn_popup = $('#addift_add_wl_btn_popup').val(); // or anything else - value taken from form
let addify_wl_product_id = $('#addify_wl_product_id').val(); // or anything else - value taken from form
$.post( ajaxurl, {
action: 'addify_get_sectiuon_btn',
addift_add_wl_btn_popup: addift_add_wl_btn_popup,
addify_wl_product_id: addify_wl_product_id
},
function ( response ) {
//do something s
} );
} );
} );
} );
} )( jQuery );
my jquery
hook
add_action( 'wp_ajax_addify_get_sectiuon_btn',array( $this, 'addify_get_sectiuon_btn'));
hook call back is
public function addify_get_sectiuon_btn() {
$wl_p_id = '';
if ( isset( $_POST['addift_add_wl_btn_popup'] ) ) {
if ( isset( $_POST['addify_wl_product_id'] ) ) {
$addify_add_to_wl_pro = sanitize_text_field( wp_unslash( $_POST ['addify_wl_product_id'] ) );
}
$addify_wl_var1 = array();
$addify_wl_var1 = WC()->session->get( 'addify_section_name' );
if ( !empty( $addify_wl_var1) ) {
$addify_wl_var2 =$addify_add_to_wl_pro;
array_push( $addify_wl_var1 ,$addify_wl_var2);
WC()->session->set( 'addify_section_name', $addify_wl_var1 );
} else {
WC()->session->set( 'addify_section_name', array($addify_add_to_wl_pro) );
}
// WC()->session->set( 'addify_section_name', null );
}
}

Checkbox field that add a subscription product and change prices of other products

In Woocommerce checkout section, I am trying to add a checkbox that adds an additional subscription product. It is working fine and I took help from here
One more requirement is that if there are other products in the cart then I want to change each product prices based on custom fields and new prices should display in the checkout.
Thanks in advance.
I used this code and working fine but product price is not changing in PayPal payment page.
// Display a custom checkout field
add_action( 'woocommerce_checkout_before_terms_and_conditions', 'custom_checkbox_checkout_field' );
function custom_checkbox_checkout_field() {
$value = WC()->session->get('add_a_product');
woocommerce_form_field( 'cb_add_product', array(
'type' => 'checkbox',
'label' => ' ' . __('Please check here to get VIP Membership'),
'class' => array('form-row-wide'),
), $value == 'yes' ? true : false );
}
// The jQuery Ajax request
add_action( 'wp_footer', 'checkout_custom_jquery_script' );
function checkout_custom_jquery_script() {
// Only checkout page
if( is_checkout() && ! is_wc_endpoint_url() ):
// Remove "ship_different" custom WC session on load
if( WC()->session->get('add_a_product') ){
WC()->session->__unset('add_a_product');
}
if( WC()->session->get('product_added_key') ){
WC()->session->__unset('product_added_key');
}
// jQuery Ajax code
?>
<script type="text/javascript">
jQuery( function($){
if (typeof wc_checkout_params === 'undefined')
return false;
$('form.checkout').on( 'change', '#cb_add_product', function(){
var value = $(this).prop('checked') === true ? 'yes' : 'no';
$.ajax({
type: 'POST',
url: wc_checkout_params.ajax_url,
data: {
'action': 'add_a_product',
'add_a_product': value,
},
success: function (result) {
$('body').trigger('update_checkout');
//console.log(result);
}
});
});
});
</script>
<?php
endif;
}
// The Wordpress Ajax PHP receiver
add_action( 'wp_ajax_add_a_product', 'checkout_ajax_add_a_product' );
add_action( 'wp_ajax_nopriv_add_a_product', 'checkout_ajax_add_a_product' );
function checkout_ajax_add_a_product() {
if ( isset($_POST['add_a_product']) ){
WC()->session->set('add_a_product', esc_attr($_POST['add_a_product']));
echo $_POST['add_a_product'];
}
die();
}
// Add remove free product
add_action( 'woocommerce_before_calculate_totals', 'adding_removing_specific_product' );
function adding_removing_specific_product( $cart ) {
if (is_admin() && !defined('DOING_AJAX'))
return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
// HERE the specific Product ID
$product_id = 179;
if( WC()->session->get('add_a_product') == 'yes' && ! WC()->session->get('product_added_key') )
{
foreach ( $cart->get_cart() as $cart_item ) {
$cart_item_key = $cart->add_to_cart( $product_id );
WC()->session->set('product_added_key', $cart_item_key);
// get the product id (or the variation id)
$product_id = $cart_item['data']->get_id();
// GET THE NEW PRICE (code to be replace by yours)
$new_price = get_post_meta( $product_id, 'pro_price_extra_info', true );
// Updated cart item price
$cart_item['data']->set_price( floatval( $new_price ) );
}
}
elseif( WC()->session->get('add_a_product') == 'no' && WC()->session->get('product_added_key') )
{
$cart_item_key = WC()->session->get('product_added_key');
$cart->remove_cart_item( $cart_item_key );
WC()->session->__unset('product_added_key');
}
}
I got solution for my above post. It might help others in future.
// Display a custom checkout field
add_action( 'woocommerce_checkout_before_terms_and_conditions', 'custom_checkbox_checkout_field' );
function custom_checkbox_checkout_field() {
$value = WC()->session->get('add_a_product');
woocommerce_form_field( 'cb_add_product', array(
'type' => 'checkbox',
'label' => ' ' . __('Please check here to get VIP Membership'),
'class' => array('form-row-wide'),
), $value == 'yes' ? true : false );
}
// The jQuery Ajax request
add_action( 'wp_footer', 'checkout_custom_jquery_script' );
function checkout_custom_jquery_script() {
// Only checkout page
if( is_checkout() && ! is_wc_endpoint_url() ):
// Remove "ship_different" custom WC session on load
if( WC()->session->get('add_a_product') ){
WC()->session->__unset('add_a_product');
}
if( WC()->session->get('product_added_key') ){
WC()->session->__unset('product_added_key');
}
// jQuery Ajax code
?>
<script type="text/javascript">
jQuery( function($){
if (typeof wc_checkout_params === 'undefined')
return false;
$('form.checkout').on( 'change', '#cb_add_product', function(){
var value = $(this).prop('checked') === true ? 'yes' : 'no';
$.ajax({
type: 'POST',
url: wc_checkout_params.ajax_url,
data: {
'action': 'add_a_product',
'add_a_product': value,
},
success: function (result) {
$('body').trigger('update_checkout');
//console.log(result);
}
});
if(value == 'no'){
window.location.reload();
}
});
});
</script>
<?php
endif;
}
// The Wordpress Ajax PHP receiver
add_action( 'wp_ajax_add_a_product', 'checkout_ajax_add_a_product' );
add_action( 'wp_ajax_nopriv_add_a_product', 'checkout_ajax_add_a_product' );
function checkout_ajax_add_a_product() {
if ( isset($_POST['add_a_product']) ){
WC()->session->set('add_a_product', esc_attr($_POST['add_a_product']));
echo $_POST['add_a_product'];
}
die();
}
// Add remove free product
add_action( 'woocommerce_before_calculate_totals', 'adding_removing_specific_product' );
function adding_removing_specific_product( $cart ) {
if (is_admin() && !defined('DOING_AJAX'))
return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
$has_sub = wcs_user_has_subscription( '', '179', 'active' );
$product_id = 179;
if( WC()->session->get('add_a_product') == 'yes' && ! WC()->session->get('product_added_key') ){
// HERE the specific Product ID
foreach ( $cart->get_cart() as $cart_item ) {
// get the product id (or the variation id)
$product_idnew = $cart_item['data']->get_id();
// GET THE NEW PRICE (code to be replace by yours)
$new_price = get_post_meta( $product_idnew, 'pro_price_extra_info', true );
$old_price = $cart_item['data']->get_price();
if($new_price == NULL){
$cart_item['data']->set_price( floatval( $old_price ) );
} else {
$cart_item['data']->set_price( floatval( $new_price ) );
}
}
$cart_item_key = $cart->add_to_cart( $product_id );
WC()->session->set('product_added_key', $cart_item_key);
} elseif( WC()->session->get('add_a_product') == 'no' && WC()->session->get('product_added_key') ) {
$cart_item_key = WC()->session->get('product_added_key');
$cart->remove_cart_item( $cart_item_key );
WC()->session->__unset('product_added_key');
}elseif ( $has_sub ) {
foreach ( $cart->get_cart() as $cart_item ) {
// get the product id (or the variation id)
$product_idnew = $cart_item['data']->get_id();
// GET THE NEW PRICE (code to be replace by yours)
$new_price = get_post_meta( $product_idnew, 'pro_price_extra_info', true );
$cart_item['data']->set_price( floatval( $new_price ) );
}
}
}
function woo_in_cart($product_id) {
global $woocommerce;
foreach($woocommerce->cart->get_cart() as $key => $val ) {
$_product = $val['data'];
if($product_id == $_product->id ) {
return true;
}
}
return false;
}
add_action( 'woocommerce_cart_loaded_from_session', 'adding_vip_product' );
function adding_vip_product( $cart ) {
$product_id = 179;
if(woo_in_cart($product_id) ) {
foreach ( $cart->get_cart() as $cart_item ) {
// get the product id (or the variation id)
$product_idnew = $cart_item['data']->get_id();
// GET THE NEW PRICE (code to be replace by yours)
$new_price = get_post_meta( $product_idnew, 'pro_price_extra_info', true );
if($new_price != 0){
$cart_item['data']->set_price( floatval( $new_price ) );
}
}
}
}

Resources