Felipe Gordillo Fries
Felipe Gordillo Fries

Reputation: 61

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 ){
        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.

Upvotes: 1

Views: 1161

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 253859

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:

Upvotes: 2

Related Questions