Call a custom user field value in a WooCommerce hooked function - php

I have created a custom field in the user profile, now I need to call the value of that field into the WooCommerce cart as a discount.
This is the function to add a custom fee in the cart:
add_action('woocommerce_cart_calculate_fees' , 'add_custom_fees');
$descuentototal = get_the_author_meta( 'descuento', $user_id );
function add_custom_fees( WC_Cart $cart ){
if( $descuentototal < 1 ){
return;
}
// Calculate the amount to reduce
$cart->add_fee( 'Discount: ', -$descuentototal);
}
But can't manage to get the value of 'descuento'.
How could I do it?
Thanks.

You need to use WordPress functions get_current_user_id() to get current user Id and get_user_meta() to get the user meta data.
So the correct code for woocommerce_cart_calculate_fees hook will be:
add_action( 'woocommerce_cart_calculate_fees', 'add_custom_fees' );
function add_custom_fees(){
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if ( !is_user_logged_in() )
return;
$user_id = get_current_user_id();
$descuentototal = get_user_meta($user_id, 'descuento', true);
if ( $descuentototal < 1 ) {
return;
} else {
$descuentototal *= -1;
// Enable translating 'Discount: '
$discount = __('Discount: ', 'woocommerce');
// Calculate the amount to reduce (without taxes)
WC()->cart->add_fee( $discount, $descuentototal, false );
}
}
Code goes in any php file of your active child theme (or theme) or also in any plugin php files.
Reference or related:
Wordpress Function Reference/get user meta
WooCommerce - Conditional Progressive Discount based on number of items in cart
WooCommerce class - WC_Cart - add_fee() method

Related

Change WooCommerce shipping method full label based on product shipping class

I want to add a custom message on the cart page in WooCommerce. The message should appear depending on the shipping class assigned to the product, in the woocommerce_cart_shipping_method_full_label hook.
I already have code that does it, but it doesn't work when I assign it to that hook, it only works if I assign it to the woocommerce_before_calculate_totals hook.
When I want to add it to the woocommerce_cart_shipping_method_full_label hook, I get the message:
Fatal error: Uncaught Error: Call to a member function get_cart()
Could someone advise me on what I'm doing wrong? I am using the storefront template with a child theme.
Based on Cart Message for a Specific Shipping Class in WooCommerce answer code, this is the code I'm using in the functions.php:
add_action( 'woocommerce_cart_shipping_method_full_label', 'cart_items_shipping_class_message', 20, 1 );
function cart_items_shipping_class_message( $cart ){
if ( ! is_cart() || ( is_admin() && ! defined( 'DOING_AJAX' ) ) )
return;
if ( did_action( 'woocommerce_cart_shipping_method_full_label' ) >= 2 )
return;
$shipping_class_id = '28'; // Your shipping class Id
// Loop through cart items
foreach( $cart->get_cart() as $cart_item ) {
// Check cart items for specific shipping class, displaying a notice
if( $cart_item['data']->get_shipping_class_id() == $shipping_class_id ){
wc_clear_notices();
wc_add_notice( sprintf( __('My custom message.', 'woocommerce'), '' . __("Pallet Shipping", "woocommerce") . ''), 'notice' );
break;
}
}
}
Mapping code written for one hook to another hook sometimes takes some tweaking, depending on the original hook and the newly mapped hook:
For example, $cart is not passed to the callback function, and hence the error message you get
wc_clear_notices() and wc_add_notice() are not applicable, as the hook you wish to use is to change the $label
if ( did_action( 'woocommerce_cart_shipping_method_full_label' ) >= 2 )
does not exist
So you get:
function filter_woocommerce_cart_shipping_method_full_label( $label, $method ) {
// Your shipping class Id
$shipping_class_id = 28;
// WC Cart
if ( WC()->cart ) {
// Get cart
$cart = WC()->cart;
// Loop through cart items
foreach ( $cart->get_cart() as $cart_item ) {
// Check cart items for specific shipping class
if ( $cart_item['data']->get_shipping_class_id() == $shipping_class_id ) {
$label = __( 'My custom message', 'woocommerce' );
break;
}
}
}
return $label;
}
add_filter( 'woocommerce_cart_shipping_method_full_label', 'filter_woocommerce_cart_shipping_method_full_label', 10, 2 );

Change payment method title for specific products in WooCommerce checkout

I'm trying that, when a specific product is in the checkout, the title of the payment method changes from; for example: "Payment by card" to "Payment in parts", is it possible?
I have tried with jquery:
jQuery(function($){
if ( $('#payment-fractional-payment').length ){
$("label[for='payment_method_redsys_gw']").text("Payment in installments");
}
});
but it only changes it for a moment and returns to the default title, is there any way to do it in the functions.php with some hook?
You can use this simple hooked function, where you will have to set the correct targeted payment id and the targeted product id(s):
add_filter( 'woocommerce_gateway_title', 'change_payment_gateway_title', 100, 2 );
function change_payment_gateway_title( $title, $payment_id ){
$targeted_payment_id = 'redsys_gw'; // Set your payment method ID
$targeted_product_ids = array(37, 53); // Set your product Ids
// Only on checkout page for specific payment method Id
if( is_checkout() && ! is_wc_endpoint_url() && $payment_id === $targeted_payment_id ) {
// Loop through cart items
foreach( WC()->cart->get_cart() as $item ) {
// Check for specific products: Change payment method title
if( in_array( $item['product_id'], $targeted_product_ids ) ) {
return __("Payment in installments", "woocommerce");
}
}
}
return $title;
}
Code goes in functions.php file of the active child theme (or active theme). It should works.

Set a custom calculated item price in Woocommerce mini-cart / Cart

Currently i have some custom calculation of product price based on different situation. When customer added a product in to cart then the custom price is set in session data , cart_item_data['my-price'] and i implemented using add_filter( 'woocommerce_add_cart_item') function and everything seems to working now .
Now the price in view cart page, checkout page is correct with my cart_item_data['my-price'].
But the only problem i am facing is the price is not updated in woocommerce mini cart that is appeared in the menu ,How can i change this ?
When i google i see a filter
add_filter('woocommerce_cart_item_price');
but i can't understand how to use this i do the following
add_filter('woocommerce_cart_item_price','modify_cart_product_price',10,3);
function modify_cart_product_price( $price, $cart_item, $cart_item_key){
if($cart_item['my-price']!==0){
$price =$cart_item['my-price'];
}
return $price;
//exit;
}
Here individual price is getting correct , but total price is wrong
Updated (october 2021)
For testing this successfully (and as I don't know how you make calculations), I have added a custom hidden field in product add to cart form with the following:
// The hidden product custom field
add_action( 'woocommerce_before_add_to_cart_button', 'add_gift_wrap_field' );
function add_gift_wrap_field() {
global $product;
// The fake calculated price
?>
<input type="hidden" id="my-price" name="my-price" value="115">
<?php
}
When product is added to cart, this my-price custom field is also submitted (posted). To set this value in cart object I use the following function:
add_filter( 'woocommerce_add_cart_item', 'custom_cart_item_prices', 20, 2 );
function custom_cart_item_prices( $cart_item_data, $cart_item_key ) {
// Get and set your price calculation
if( isset( $_POST['my-price'] ) ){
$cart_item_data['my-price'] = $_POST['my-price'];
// Every add to cart action is set as a unique line item
$cart_item_data['unique_key'] = md5( microtime().rand() );
}
return $cart_item_data;
}
Now to apply (set) the new calculated price my-price to the cart item, I use this last function:
// For mini cart *(cart item displayed price)*
add_action( 'woocommerce_cart_item_price', 'filter_cart_item_price', 10, 2 );
function filter_cart_item_price( $price, $cart_item ) {
if ( ! is_checkout() && isset($cart_item['my-price']) ) {
$args = array( 'price' => floatval( $cart_item['my-price'] ) );
if ( WC()->cart->display_prices_including_tax() ) {
$product_price = wc_get_price_including_tax( $cart_item['data'], $args );
} else {
$product_price = wc_get_price_excluding_tax( $cart_item['data'], $args );
}
return wc_price( $product_price );
}
return $price;
}
add_action( 'woocommerce_before_calculate_totals', 'set_calculated_cart_item_price', 20, 1 );
function set_calculated_cart_item_price( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
return;
// Loop through cart items
foreach ( $cart->get_cart() as $cart_item ){
if( isset( $cart_item['my-price'] ) && ! empty( $cart_item['my-price'] ) || $cart_item['my-price'] != 0 ){
// Set the calculated item price (if there is one)
$cart_item['data']->set_price( $cart_item['my-price'] );
}
}
}
All code goes in function.php file of your active child theme (or active theme).
Tested and works

Hide shipping methods for specific shipping class in WooCommerce

Essentially I'm trying to make the flat rate method Id flat_rate:7 disabled when there is cart items that have the shipping class "Roller" (ID 92).
This is the code I tried:
add_filter('woocommerce_package_rates', 'wf_hide_shipping_method_based_on_shipping_class', 10, 2);
function wf_hide_shipping_method_based_on_shipping_class($available_shipping_methods, $package)
{
$hide_when_shipping_class_exist = array(
92 => array(
'flat_rate:7'
)
);
$shipping_class_in_cart = array();
foreach(WC()->cart->cart_contents as $key => $values) {
$shipping_class_in_cart[] = $values['data']->get_shipping_class_id();
}
foreach($hide_when_shipping_class_exist as $class_id => $methods) {
if(in_array($class_id, $shipping_class_in_cart)){
foreach($methods as & $current_method) {
unset($available_shipping_methods[$current_method]);
}
}
}
return $available_shipping_methods;
}
Shipping class ID 92 is the shipping class and I want to hide flat_rate:7 for it.
My Site is this: http://www.minimoto.me/
WordPress: 4.8.4
WooCommerce: 3.1.1
Any help will be greatly appreciated.
Update 2019: You should try instead this shorter, compact and effective way:
add_filter( 'woocommerce_package_rates', 'hide_shipping_method_based_on_shipping_class', 10, 2 );
function hide_shipping_method_based_on_shipping_class( $rates, $package )
{
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// HERE define your shipping class to find
$class = 92;
// HERE define the shipping method to hide
$method_key_id = 'flat_rate:7';
// Checking in cart items
foreach( $package['contents'] as $item ){
// If we find the shipping class
if( $item['data']->get_shipping_class_id() == $class ){
unset($rates[$method_key_id]); // Remove the targeted method
break; // Stop the loop
}
}
return $rates;
}
Code goes in function.php file of your active child theme (or theme) or also in any plugin file.
Tested and works.
Sometimes, you should may be need to refresh shipping methods going to shipping areas, then disable / save and re-enable / save your "flat rates" shipping methods.
Related: Hide shipping methods for specific shipping classes in WooCommerce
To find the shipping methods IDs and the shipping classes IDs see below…
Update for many different shipping methods (related to your comments):
add_filter( 'woocommerce_package_rates', 'hide_shipping_method_based_on_shipping_class', 10, 2 );
function hide_shipping_method_based_on_shipping_class( $rates, $package )
{
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// HERE define your shipping class to find
$class = 92;
// HERE define the shipping methods you want to hide
$method_key_ids = array('flat_rate:7', 'local_pickup:3');
// Checking in cart items
foreach( $package['contents'] as $item ) {
// If we find the shipping class
if( $item['data']->get_shipping_class_id() == $class ){
foreach( $method_key_ids as $method_key_id ){
unset($rates[$method_key_id]); // Remove the targeted methods
}
break; // Stop the loop
}
}
return $rates;
}
Tested and works…
Finding the shipping class ID.
In the database under wp_terms table:
Search for a term name or a term slug and you will get the term ID (the shipping class ID).
On Woocommerce shipping settings editing a "Flat rate", with your browser html inspector tool, inspect a shipping Class rate field like:
In the imput name attribute you have woocommerce_flat_rate_class_cost_64. So 64 is the ID for the shipping class.
Get the shipping method rate ID:
To get the related shipping methods rate IDs, something like flat_rate:12, inspect with your browser code inspector each related radio button attribute value like:
By tweaking LoicTheAztec's code (cheers), I was able to unset a shipping method for each package based on the shipping class of its contents, rather than the cart as a whole. Perhaps it will help someone else too:
// UNSET A SHIPPING METHOD FOR PACKAGE BASED ON THE SHIPPING CLASS(es) OF ITS CONTENTS
add_filter( 'woocommerce_package_rates', 'hide_shipping_method_based_on_shipping_class', 10, 2 );
function hide_shipping_method_based_on_shipping_class( $rates, $package )
{
if ( is_admin() && ! defined( 'DOING_AJAX' ) ) {
return;
}
foreach( $package['contents'] as $package_item ){ // Look at the shipping class of each item in package
$product_id = $package_item['product_id']; // Grab product_id
$_product = wc_get_product( $product_id ); // Get product info using that id
if( $_product->get_shipping_class_id() != 371 ){ // If we DON'T find this shipping class ID
unset($rates['wbs:9:dae98e94_free_ups_ground']); // Then remove this shipping method
break; // Stop the loop, since we've already removed the shipping method from this package
}
}
return $rates;
}
This code allows me to unset my 'Free UPS Ground' shipping if the package contains anything but 'Standard' items (shipping_class_id 371 in my case).
The scenario from the original post (disable method x if shipping class y) would work like this:
// UNSET A SHIPPING METHOD FOR PACKAGE BASED ON THE SHIPPING CLASS(es) OF ITS CONTENTS
add_filter( 'woocommerce_package_rates', 'hide_shipping_method_based_on_shipping_class', 10, 2 );
function hide_shipping_method_based_on_shipping_class( $rates, $package )
{
if ( is_admin() && ! defined( 'DOING_AJAX' ) ) {
return;
}
foreach( $package['contents'] as $package_item ){ // Look at the shipping class of each item in package
$product_id = $package_item['product_id']; // Grab product_id
$_product = wc_get_product( $product_id ); // Get product info using that id
if( $_product->get_shipping_class_id() == 92 ){ // If we DO find this shipping class ID
unset($rates['flat_rate:7']); // Then remove this shipping method
break; // Stop the loop, since we've already removed the shipping method from this package
}
}
return $rates;
}

Add fee based on specific payment methods in WooCommerce

In WooCommerce I need to apply a custom handling fee for a specific payment gateway. I have this piece of code from here: How to Add Handling Fee to WooCommerce Checkout.
This is my code:
add_action( 'woocommerce_cart_calculate_fees','endo_handling_fee' );
function endo_handling_fee() {
global $woocommerce;
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
$fee = 5.00;
$woocommerce->cart->add_fee( 'Handling', $fee, true, 'standard' );
}
This function add a fee to all transactions.
Is it possible to tweak this function and make it apply for specific payment method only ?
The other problem is that I want this fee to be applied on cart. Is it possible?
I will welcome any alternative method as well. I know about the similar "Payment Gateway Based Fees" woo plugin, but I can't afford it.
2021 UPDATE
Note: All payment methods are only available on Checkout page.
The following code will add conditionally a specific fee based on the chosen payment method:
// Add a custom fee (fixed or based cart subtotal percentage) by payment
add_action( 'woocommerce_cart_calculate_fees', 'custom_handling_fee' );
function custom_handling_fee ( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
$chosen_payment_id = WC()->session->get('chosen_payment_method');
if ( empty( $chosen_payment_id ) )
return;
$subtotal = $cart->subtotal;
// SETTINGS: Here set in the array the (payment Id) / (fee cost) pairs
$targeted_payment_ids = array(
'cod' => 8, // Fixed fee
'paypal' => 5 * $subtotal / 100, // Percentage fee
);
// Loop through defined payment Ids array
foreach ( $targeted_payment_ids as $payment_id => $fee_cost ) {
if ( $chosen_payment_id === $payment_id ) {
$cart->add_fee( __('Handling fee', 'woocommerce'), $fee_cost, true );
}
}
}
You will need the following to refresh checkout on payment method change, to get it work:
// jQuery - Update checkout on payment method change
add_action( 'woocommerce_checkout_init', 'payment_methods_refresh_checkout' );
function payment_methods_refresh_checkout() {
wc_enqueue_js( "jQuery( function($){
$('form.checkout').on('change', 'input[name=payment_method]', function(){
$(document.body).trigger('update_checkout');
});
});");
}
Code goes in functions.php file of your active child theme (or active theme). tested and works.
How to find a specific payment method ID in WooCommerce Checkout page?
The following will display on checkout payment methods the payment Id just for admins:
add_filter( 'woocommerce_gateway_title', 'display_payment_method_id_for_admins_on_checkout', 100, 2 );
function display_payment_method_id_for_admins_on_checkout( $title, $payment_id ){
if( is_checkout() && ( current_user_can( 'administrator') || current_user_can( 'shop_manager') ) ) {
$title .= ' <code style="border:solid 1px #ccc;padding:2px 5px;color:red;">' . $payment_id . '</code>';
}
return $title;
}
Code goes in functions.php file of your active child theme (or active theme). Once used, remove it.
Similar answer:
Add a custom fee for a specific payment gateway in Woocommerce
Add a fee based on shipping method and payment method in Woocommerce
Percentage discount based on user role and payment method in Woocommerce
First of all there are some key things we need to understand:
We are going to use the only filter hook which is woocommerce_cart_calculate_fees
In order to get user selected payment method we must retrieve it from user sessions using this method WC()->session->get( 'chosen_payment_method' )
calculate_fees() and calculate_totals() methods are not necessary.
We are going to add the fee using cart method WC()->cart->add_fee() which accepts two parameters – the first one, is the fee description, the second one – fee amount.
And one more thing – we will need a payment method slug, the easiest way to get it described in this tutorial https://rudrastyh.com/woocommerce/add-id-column-to-payment-methods-table.html
Let's go now:
add_action( 'woocommerce_cart_calculate_fees', 'rudr_paypal_fee', 25 );
function rudr_paypal_fee() {
if( 'paypal' == WC()->session->get( 'chosen_payment_method' ) ) {
WC()->cart->add_fee( 'PayPal fee', 2 ); // let's add a fee for paypal
}
}
It would be also great to refresh the checkout every time payment gateway is changed, it is easy to do using this code:
jQuery( function( $ ) {
$( 'form.checkout' ).on( 'change', 'input[name^="payment_method"]', function() {
$( 'body' ).trigger( 'update_checkout' );
});
});
That's it. Everything is described in details here as well: https://rudrastyh.com/woocommerce/charge-additional-fees-based-on-payment-gateway.html
For anyone else looking to do this, I wanted to add a fee for Bank Transfers (BACS), here is the method I used:
//Hook the order creation since it is called during the checkout process:
add_filter('woocommerce_create_order', 'my_handle_bacs', 10, 2);
function my_handle_bacs($order_id, $checkout){
//Get the payment method from the $_POST
$payment_method = isset( $_POST['payment_method'] ) ? wc_clean( $_POST['payment_method'] ) : '';
//Make sure it's the right payment method
if($payment_method == "bacs"){
//Use the cart API to add recalculate fees and totals, and hook the action to add our fee
add_action('woocommerce_cart_calculate_fees', 'my_add_bacs_fee');
WC()->cart->calculate_fees();
WC()->cart->calculate_totals();
}
//This filter is for creating your own orders, we don't want to do that so return the $order_id untouched
return $order_id;
}
function my_add_bacs_fee($cart){
//Add the appropriate fee to the cart
$cart->add_fee("Bank Transfer Fee", 40);
}
add_action( 'woocommerce_cart_calculate_fees','cod_fee' );
function cod_fee() {
global $woocommerce;
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// get your payment method
$chosen_gateway = WC()->session->chosen_payment_method;
//echo $chosen_gateway;
$fee = 5;
if ( $chosen_gateway == 'cod' ) { //test with cash on delivery method
WC()->cart->add_fee( 'delivery fee', $fee, false, '' );
}
}

Categories