Search code examples
wordpresshttp-redirectwoocommerceuser-data

Auto redirection in WooCommerce after login based on user meta data


I am trying to check if a user meta data is empty or not. If empty, redirect the user to a page, else redirect to the default page.

But my following codes is only redirecting to the default page.

add_filter('woocommerce_login_redirect', 'ac_my_acct_login_redirect');

function ac_my_acct_login_redirect($redirect_to) {
    $user_id = get_current_user_id();
    $father = get_user_meta( $user_id, 'fath_name', true ); 
    $update_pro = esc_url(get_permalink('123')); // the page I want for redirection if metadata is empty
    $my_acct = esc_url(get_permalink( wc_get_page_id( 'myaccount' ) )); // default woocommerce my account page

    if(empty($father)){
    $redirect_to = $update_pro;
    }
    else {
    $redirect_to = $my_acct;
    }
    return $redirect_to;
}

meta key = fath_name (even it has value, still the redirection is not working as intended). Any advice?


Solution

  • Your code contains some mistakes

    • get_current_user_id() is not necessary, as $user is passed to the callback function
    • get_permalink() expects an int (123), not a string ("123")
    • Make sure the page ID actually exists

    So you get:

    function filter_woocommerce_login_redirect( $redirect, $user ) {    
        // Get user meta
        $value = get_user_meta( $user->ID, 'fath_name', true );
    
        // Empty
        if ( empty( $value ) ) {
            $redirect = get_permalink( 123 );
        } else {
            // Get the "My account" url
            $redirect = get_permalink( wc_get_page_id( 'myaccount' ) );     
        }
        
        return $redirect;
    }
    add_filter( 'woocommerce_login_redirect', 'filter_woocommerce_login_redirect', 10, 2 );