WooCommerce get cart information from postmeta - php

I have written a function that should add discount amounts on the woo cart, depends on product combination and custom fields.
If the action is wp_footer i can see get_post_meta works well.
But if I write action to be woocommerce_cart_calculate_fees seems not to work fine.
Can anyone help me with getting into the right direction? Thanks
Here is my code and screenshot below for it:
add_action('woocommerce_cart_calculate_fees', 'action_woocommerce_cart_calculate_fees2');
function action_woocommerce_cart_calculate_fees2($cart) {
// if ( is_admin() && ! defined( 'DOING_AJAX' ) )
// return;
//if ( did_action( 'woocommerce_before_calculate_totals' ) >= 1 )
//return;
//$cart = WC()->cart->get_cart();
foreach ( $cart as $cart_item_key => $cart_item ) {
// Get product id
$product_id = $cart_item['product_id'];
$product = wc_get_product($product_id);
//echo $product_id . "<br>";
$is_enable = get_post_meta( $product_id, '_enable_promo_for_current_product', true );
if ($is_enable == 'yes') {
$product_arr[] = $product_id;
}
}
foreach ( $product_arr as $val ) {
$product = wc_get_product($val);
$otstapka = get_post_meta( $val, '_procent_otstapka_promo', true );
if (empty($otstapka)) {
$otstapka = 10;
}
$value = get_post_meta( $val, 'wc_product_ids', true );
if ( ! empty( $value ) ) {
$promo_product = wc_get_product( $value );
$name = $promo_product->name;
$price = $promo_product->get_price();
$sale_price = $price * (1 - ($otstapka / 100));
$otstapka2 = $price - $sale_price;
$product_promo_id = $promo_product->get_id();
if ( check_variation_is_in_cart($val) ) {
$cart->add_fee('Отстъпка за промо пакет', -$otstapka2, false);
}
}
}
}

Related

Fatal error: Uncaught Error: Unsupported operand types when using the minus - sign

I think this has something to do with using strings and arrays with the number field and minus operator -
This only happens on variable products so i think it relates to child products and i need to use array_sum() to calculate the sum in multi-dimensional arrays
add_filter('woocommerce_is_purchasable', 'non_purchasable_oos_threshold', 10, 2 );
function non_purchasable_oos_threshold( $is_purchasable, $product ) {
$product_id = $product->get_id();
$stock_threshold = get_post_meta( $product_id, '_out_of_stock_threshold', true );
$threshold = $product->get_meta( '_out_of_stock_threshold' );
if ( $product->managing_stock() && ! empty( $threshold ) ) {
$stock = $product->get_stock_quantity();
$new_stock_quantity = $product->get_stock_quantity() - $threshold;
// var_dump($new_stock_quantity);
if ( $new_stock_quantity == 0 ) {
return false;
}
return $is_purchasable;
}
}
Why am i getting this error as it says its coming from the minus operator - but i doubt that's the real reason and think it has something to do with my code.
Update : I also tried this for variations :
add_filter('woocommerce_is_purchasable', 'variations_purchasable_oos_threshold', 10, 2 );
function variations_purchasable_oos_threshold( $is_purchasable, $product ) {
if ( $product->get_type() == 'variable' ) {
foreach ( $product->get_available_variations() as $key ) {
$variation = wc_get_product( $key['variation_id'] );
$stock = $variation->get_availability();
$product_id = $product->get_id();
$stock_threshold = get_post_meta( $product_id, '_out_of_stock_threshold', true );
$threshold = $product->get_meta( '_out_of_stock_threshold' );
if ( $product->managing_stock() && ! empty( $threshold ) ) {
$stock = $product->get_stock_quantity();
$new_stock_quantity = $stock - $threshold;
// var_dump($new_stock_quantity);
if ( $new_stock_quantity == 0 ) {
return false;
}
return $is_purchasable;
} }
}
}
1 added
(int) get_post_meta( $product_id, '_out_of_stock_threshold', true );
If the string is numeric, resolve to an int if the string is an integer numeric string.

Display variable product discounted percentage only on Woocommerce archive pages

I'd like to display the percentage variable products are discounted in the archive pages. With the code below, I was able to get both the discounts % on variable products but also for simple products. Can I do this ONLY for variable products and not simple products? I realize it's probably a simple adjustment in the code but I can't figure it out because I'm an idiot when it comes to PHP.
add_action( 'woocommerce_after_shop_loop_item', 'show_sale_percentage', 25 );
function show_sale_percentage() {
global $product;
if ( $product->is_on_sale() ) {
if ( ! $product->is_type( 'variable' ) ) {
$max_percentage = ( ( $product->get_regular_price() - $product->get_sale_price() ) / $product->get_regular_price() ) * 100;
} else {
$max_percentage = 0;
foreach ( $product->get_children() as $child_id ) {
$variation = wc_get_product( $child_id );
$price = $variation->get_regular_price();
$sale = $variation->get_sale_price();
if ( $price != 0 && ! empty( $sale ) ) $percentage = ( $price - $sale ) / $price * 100;
if ( $percentage > $max_percentage ) {
$max_percentage = $percentage;
}
}
}
echo "<div class='saved-sale'>-" . round($max_percentage) . "%</div>";
}
}
To display the on sale percentage, on archives pages, for variable products only, try the following:
add_action( 'woocommerce_after_shop_loop_item', 'loop_variable_product_sale_percentage', 25 );
function loop_variable_product_sale_percentage() {
global $product;
if ( $product->is_on_sale() && $product->is_type( 'variable' ) ) {
$max_percentage = 0;
foreach ( $product->get_children() as $child_id ) {
$variation = wc_get_product( $child_id );
$percentage = 0;
$price = $variation->get_regular_price();
$sale = $variation->get_sale_price();
if ( $price != 0 && ! empty( $sale ) ) {
$percentage = ( $price - $sale ) / $price * 100;
}
if ( $percentage > $max_percentage ) {
$max_percentage = $percentage;
}
}
echo '<div class="saved-sale">-' . round($max_percentage) . '%</div>';
}
}
Code goes in function.php file of your active child theme (or active theme). Tested and works.

Set product variation custom calculated price dynamically in WooCommerce

I am trying to dynamically add to a products price when a user checks out based on what they have entered in the product page. The setting of the price is only working on a non variation product.
I need to be able to set the price on the variations of the products as well.
The code that I am using:
function add_cart_item_data( $cart_item_meta, $product_id, $variation_id ) {
$product = wc_get_product( $product_id );
$price = $product->get_price();
$letterCount = strlen($_POST['custom_name']);
$numberCount = strlen($_POST['custom_number']);
if($letterCount != '0') {
$letterPricing = 20 * $letterCount;
$numberPricing = 10 * $numberCount;
$additionalPrice = $letterPricing + $numberPricing;
$cart_item_meta['custom_price'] = $price + $additionalPrice;
}
return $cart_item_meta;
}
function calculate_cart_total( $cart_object ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) ) {
return;
}
foreach ( $cart_object->cart_contents as $key => $value ) {
if( isset( $value['custom_price'] ) ) {
$price = $value['custom_price'];
$value['data']->set_price( ( $price ) );
}
}
}
I have completely revisited your code:
// Set custom data as custom cart data in the cart item
add_filter( 'woocommerce_add_cart_item_data', 'add_custom_data_to_cart_object', 30, 3 );
function add_custom_data_to_cart_object( $cart_item_data, $product_id, $variation_id ) {
if( ! isset($_POST['custom_name']) || ! isset($_POST['custom_number']) )
return $cart_item_data; // Exit
if( $variation_id > 0)
$product = wc_get_product( $variation_id );
else
$product = wc_get_product( $product_id );
$price = $product->get_price();
// Get the data from the POST request and calculate new custom price
$custom_name = sanitize_text_field( $_POST['custom_name'] );
if( strlen( $custom_name ) > 0 )
$price += 20 * strlen( $custom_name );
$custom_number = sanitize_text_field( $_POST['custom_number'] );
if( strlen( $custom_number ) > 0 )
$price += 10 * strlen( $custom_number );
// Set new calculated price as custom cart item data
$cart_item_data['custom_data']['price'] = $price;
return $cart_item_data;
}
// Set the new calculated price of the cart item
add_action( 'woocommerce_before_calculate_totals', 'set_new_cart_item_price', 50, 1 );
function set_new_cart_item_price( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
foreach ( $cart->get_cart() as $cart_item ) {
if( isset( $cart_item['custom_data']['price'] ) ) {
// Get the new calculated price
$new_price = (float) $cart_item['custom_data']['price'];
// Set the new calculated price
$cart_item['data']->set_price( $new_price );
}
}
}
This code goes on function.php file of your active child theme (or theme).
Tested and works as well with product variations.

Determine language in functions.php [wpml]

I have function in functions.php , which automatically adds woocommerce product by ID to cart when website is visited.
The website is bilingual and the function can't determine translated product ID.
So, I want to know if is possible to add wpml function in functions.php, which determines first language of front end, then executes function, something like this:
<?php if(wpml_getLanguage()=='en'); ?>
---do function for product 22---
<?php elseif(wpml_getLanguage()=='it'); ?>
---do function for product 45--
<?php endif; ?>
My code:
add_action( 'template_redirect', 'add_product_to_cart' );
function add_product_to_cart() {
if ( ! is_admin() ) {
$product_id = 22;
$found = false;
//check if product already in cart
if ( sizeof( WC()->cart->get_cart() ) > 0 ) {
foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
$_product = $values['data'];
if ( $_product->id == $product_id )
$found = true;
}
// if product not found, add it
if ( ! $found )
WC()->cart->add_to_cart( $product_id );
} else {
// if no products in cart, add it
WC()->cart->add_to_cart( $product_id );
}
}
}
You can easily get this by using the native WPML variable ICL_LANGUAGE_CODE.
You can find more information about this topic on the following page:
https://wpml.org/documentation/support/wpml-coding-api/
This can be dropped into functions.php
add_action( 'init', 'add_product_on_language' );
function add_product_on_language(){
if ( ! is_admin() ) {
if( ICL_LANGUAGE_CODE == 'en' ){
$product_id = 22;
} elseif ( ICL_LANGUAGE_CODE == 'it' ) {
$product_id = 45;
}
$found = false;
//check if product already in cart
if ( sizeof( WC()->cart->get_cart() ) > 0 ) {
foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
$_product = $values['data'];
if ( $_product->id == $product_id )
$found = true;
}
// if product not found, add it
if ( ! $found )
WC()->cart->add_to_cart( $product_id );
} else {
// if no products in cart, add it
WC()->cart->add_to_cart( $product_id );
}
}
}

Woocommerce Is_Purchasable cause ajax error

I'm using the code below to modify the WooCommerce Is_Purchasable option so that, item Y is purchasable if item X is added to the cart.
But it gives ajax error when trying to add item Y to the cart.
Here's the code:
function aelia_get_cart_contents() {
$cart_contents = array();
/**
* Load the cart object. This defaults to the persistant cart if null.
*/
$cart = WC()->session->get( 'cart', null );
if ( is_null( $cart ) && ( $saved_cart = get_user_meta( get_current_user_id(), '_woocommerce_persistent_cart', true ) ) ) {
$cart = $saved_cart['cart'];
} elseif ( is_null( $cart ) ) {
$cart = array();
}
if ( is_array( $cart ) ) {
foreach ( $cart as $key => $values ) {
$_product = wc_get_product( $values['variation_id'] ? $values['variation_id'] : $values['product_id'] );
if ( ! empty( $_product ) && $_product->exists() && $values['quantity'] > 0 ) {
if ( $_product->is_purchasable() ) {
// Put session data into array. Run through filter so other plugins can load their own session data
$session_data = array_merge( $values, array( 'data' => $_product ) );
$cart_contents[ $key ] = apply_filters( 'woocommerce_get_cart_item_from_session', $session_data, $values, $key );
}
}
}
}
return $cart_contents;
}
// Step 1 - Keep track of cart contents
add_action('wp_loaded', function() {
// If there is no session, then we don't have a cart and we should not take
// any action
if(!is_object(WC()->session)) {
return;
}
// Product Y
global $y_cart_items;
$y_cart_items = 2986;
//Product X
global $x_cart_items;
$x_cart_items = array(
'297'
);
// Step 2
add_filter('woocommerce_is_purchasable', function($is_purchasable, $product) {
global $y_cart_items;
global $x_cart_items;
if( $product->id == $y_cart_items ) {
// make it false
$is_purchasable = false;
// get the cart items object
foreach ( aelia_get_cart_contents() as $key => $item ) {
// do your condition
if( in_array( $item['product_id'], $x_cart_items ) ) {
// Eligible product found on the cart
$is_purchasable = true;
break;
}
}
}
return $is_purchasable;
}, 10, 2);
}, 10);
// Step 3 - Explain customers why they can't add some products to the cart
add_filter('woocommerce_get_price_html', function($price_html, $product) {
if(!$product->is_purchasable() && is_product()) {
$price_html .= '<p>' . __('Add Product X to be able to purchase Product Y.', 'woocommerce') . '</p>';
}
return $price_html;
}, 10, 2);
How do I fix this? Thank you.

Categories