Felipe Gordillo Fries Felipe Gordillo Fries - 9 months ago 53
PHP Question

Call a custom user field value in a WooCommerce hooked function

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 ){
// 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?


Answer Source

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' ) )

    if ( !is_user_logged_in() )

    $user_id = get_current_user_id();
    $descuentototal = get_user_meta($user_id, 'descuento', true);

    if ( $descuentototal < 1 ) {
    } 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: