Update Specific product subtotal in woo-commerce cart - wordpress

foreach( $cart as $cart_item_id => $citem ) {
if ( $citem['product_id'] == $gift ) {
$item_id = $cart_item_id;
$grp = $citem['data']->get_regular_price();
//$woocommerce->cart->cart_contents[$cart_item_id]['line_subtotal'] = 1;
$woocommerce->cart->line_subtotal($cart_item_id, '0');
$woocommerce->cart->cart_contents[$cart_item_id]['line_subtotal'] = 1;
//WC()->cart->set_session();
//$woocommerce->cart->set_session();
}
}
I can get access to cart details in "woocommerce_before_calculate_totals" hook.
But I can not manage to change the line_subtotal of a specific product.
Is there any way to do it using "woocommerce_before_calculate_totals" hook?
Thanks in advance.

There is a way doing this using woocommerce_before_calculate_totals, but as you do that it would also affect the individual price of the product.
So if you choose to do this, you would have to reset the individual price of the product by then filtering woocommerce_cart_item_price.
But this is kind of wierd so I would try using woocommerce_cart_item_subtotal, if it works in your usecase.
add_filter('woocommerce_cart_item_subtotal','new_cart_item_subtotal_filter', 10, 3);
function new_cart_item_subtotal_filter( $oldTotal, $cart_item, $cart_item_key){
//filter...
return $oldTotal;
}

Related

Solution to changing currency for Woocommerce products

Hi so I would like to be able to change currency for different products added to the cart/checkout.
I found solution that is filtering woocommerce_currency hook and using cart session to change currency.
Two questions:
Is there a better way of doing it?
Do you see any potential problems with the following solution?
public function modifyWoocommerceCurrency( $currency ) {
$cart_data = WC()->session->get('cart');
foreach ($cart_data as $item) {
if (isset($item["_campaign_options"]["user_paying_currency"])) {
$currency = $item['_campaign_options']['user_paying_currency'];
}
}
return $currency;
}
add_filter( 'woocommerce_currency', [$this,'modifyWoocommerceCurrency'], 10, 1 );

In WooCommerce, Is it possible to display specific country only if cart total is over 100?

I have tried to do it using a filter hook called "woocommerce_countries". I tried getting the cart total in this hook but it's not working. Is anyone have any idea on this OR suggest any hook?
Please try with this code. WooCommerce 3.6.2, they have removed the ability to check the cart data. But cart session is accessible right now so we use this function WC()->session->cart
add_filter( 'woocommerce_countries', 'products_disable_country', 10, 1 );
function products_disable_country( $countries ) {
$cartdata = WC()->session->cart;
if (is_array($cartdata) && !empty($cartdata)) {
foreach ($cartdata as $itemdata) {
$sum += $itemdata['line_total'];
}
if ($sum >= 100) {
unset($countries["CA"]);
}
}
return $countries;
}

Display default and selected variation price from a woocommerce variable product

I've been looking over Stack for an answer but can't find one (even when reading this and this)
Here my trouble: i would like to display (or at least get the variable) of the default and selected price of a woocommerce variable product.
System: Wordpress 5,6 + woocommerce
With a single product, my code is working well and i obtain a display like this:
Display for a single product with weight and price rewritten on right after quantity selector
And code is the following:
global $woocommerce;
$productxyz = new WC_Product( get_the_ID() );
$priceproduct = $productxyz->get_regular_price();
$poidsproduct = $productxyz->get_weight();
// CODE FOR THE + AND - QUANTITY
var $ = jQuery;
$(document).ready(function(){
$('.decrement').click(function () {
$moninput = $(this).nextAll('input#Qte');
if( Number($moninput.val()) > $moninput.attr("min") ){
$moninput.val(Number($moninput.val()) - 1);
}else{
$moninput.val($moninput.attr("min"));
}
Update_Price();
event.preventDefault();
})
$('.increment').click(function () {
$moninput = $(this).nextAll('input#Qte');
$moninput.val(Number($moninput.val()) + 1);
Update_Price();
event.preventDefault();
})
$('#btn-cady').click(function () {
$('[name="add-to-cart"]').click();
event.preventDefault();
})
// CODE FOR THE TEXT DISPLAYED ON THE RIGHT OF THE QUANTITY SELECTOR
function Update_Price(){
if($('input#Qte').attr('price') > 0){
$total = parseFloat($('input#Qte').val()) * $('input#Qte').attr('price');
$qtyactuelle = parseFloat($('input#Qte').val());
$('input[name="quantity"]').val($('input#Qte').val());
console.log($total);
if( $qtyactuelle < 2){
$('.Qtotal h4').html("<font color='#401816'>pack soit " +($('input#Qte').attr('weight')*parseFloat($('input#Qte').val()))+"g |</font> "+parseFloat($total).toFixed(2)+" €");
}
if($qtyactuelle > 1){
$('.Qtotal h4').html("<font color='#401816'>packs soit " +($('input#Qte').attr('weight')*parseFloat($('input#Qte').val()))+"g |</font> "+parseFloat($total).toFixed(2)+" €");
}
}
}
Update_Price();
});
But for a variation product... i feel so ashamed to show my result because when it's displaying well, function is not working. And when functions are working, display is very terrible
Code result for variation product
I tried to use get_available_variations() and also the following foreach but...
foreach( $product->get_available_variations() as $variation ){
$found = true;
// Loop through variation attributes
foreach( $variation['attributes'] as $key => $value ){
$taxonomy = str_replace( 'attribute_', '', $key );
// Searching for a matching variation as default
if( isset($default_attributes[$taxonomy]) && $default_attributes[$taxonomy] != $value ){
$found = false;
break;
}
}
// If we get the default variation
if( $found ) {
$default_variaton = $variation;
break;
}
Has anyone an idea of how to developp it? I'm feeling speechless.
In advance, thanks a lot!!!
On WooCommerce variable product pages, product variation data is stored in the data-product_variations attribute of the multi-select <form class="variation_form"> element. The variation data is stored in JSON format which you can then decode using the JSON.parse() method. There is no need to output this data yourself via PHP as WooCommerce already does it for you.
The JSON stored in the data-product_variations attribute includes the following price related properties:
display_price
regular_price
sale_price
With a little bit of jQuery/JS, you can easily output or mutate the default or selected variation pricing with the above properties.
Good Luck!

How can I do in Woocommerce to apply discounts only for logged users?

I´m looking for a hook that can help me apply discounts only in case that user is logged. Every one can see the discount but it is applyed only for registered users.
You can use the conditional tag is_user_logged_in() in an IF statement inside any function that you can pick in any of those related threads, to restrict it only for logged users.
If you choose the right working code, it will recalculate the totals by itself for logged in users (just as well as if it was without restrictions).
Solved.
Sharing my solution:
add_action( 'woocommerce_before_calculate_totals', 'no_discount_if_not_logged_in', 10, 1);
function no_discount_if_not_logged_in( $cart ) {
if (!is_user_logged_in()) {
foreach ( $cart->get_cart() as $cart_item ) {
$descount_eliminate = $cart_item['data']->get_regular_price();
$cart_item['data']->set_price($descount_eliminate );
}
}
}

Hide Shipping Options Woocommerce

So I'm trying to hide certain ship methods in Woocommerce based on a product tag. The main problem I face is my own lack PHP knowledge so I frankensteined the following code together with the help of some very friendly folks:
add_filter( 'woocommerce_available_shipping_methods', 'hide_shipping_based_on_tag' , 10, 1 );
function check_cart_for_share() {
// load the contents of the cart into an array.
global $woocommerce;
$cart = $woocommerce->cart->cart_contents;
$found = false;
// loop through the array looking for the tag you set. Switch to true if the tag is found.
foreach ($cart as $array_item) {
if (isset($array_item['product_tag']) && $array_item['product_tag'] == "CHOSEN_TAG") { // Replace "CHOSEN_TAG" with what ever tag you want
$found = true;
break;
}
}
return $found;
}
function hide_shipping_based_on_tag( $available_methods ) {
// use the function abve to check the cart for the tag.
if ( check_cart_for_share() ) {
// remove the rate you want
unset( $available_methods['flat_rate'] ); // Replace "flar_rate" with the shipping option that yu want to remove.
}
// return the available methods without the one you unset.
return $available_methods;
}
I understand that this code is by no means universal and thus the variables will be different from case to case but perhaps someone can tell me if something looks off in the code. Much appreciated
No doubt you have sorted this by now but your code was a good start for me ... and since I sorted it I have published it below. Your problem was that woocommerce doesn't have the product_tag in the cart array so you have to go and get it.
/* !Hide Shipping Options Woocommerce */
add_filter( 'woocommerce_available_shipping_methods', 'hide_shipping_based_on_tag' , 10, 1 );
function check_cart_for_share() {
// load the contents of the cart into an array.
global $woocommerce;
$cart = $woocommerce->cart->cart_contents;
$found = false;
// loop through the array looking for the tag you set. Switch to true if the tag is found.
foreach ($cart as $array_item) {
$term_list = wp_get_post_terms( $array_item['product_id'], 'product_tag', array( "fields" => "names" ) );
if (in_array("Heavy",$term_list)) { // Replace "Heavy" with what ever tag you want
$found = true;
break;
}
}
return $found;
}
function hide_shipping_based_on_tag( $available_methods ) {
// use the function above to check the cart for the tag.
if ( check_cart_for_share() ) {
// remove the rate you want
unset( $available_methods['flat_rate'] ); // Replace "flat_rate" with the shipping option that you want to remove.
}
// return the available methods without the one you unset.
return $available_methods;
}
You can use shipping class of Woocommerce to achieve this.
Here is the step by step instructions.
Create a shipping class (woocommerce->settings->shipping->shipping classes).
Associate this shipping class with products (that you wand to hide shipping methods for)
Use this snippet. (copy and pate to function.php).
For more information about the snippet is available here.

Resources