Search code examples
phpwordpresswoocommercewordpress-hook

WP/WC missing argument in WooCommerce Function


I have Wordpress with WooCommerce installed and I am trying to use this code to login an admin user:

if ( !is_user_logged_in() ) {
    $user = get_userdatabylogin( $username ); // get_user_by('login', $user_login);
    $id = $user->ID;

    wp_set_current_user( $id, $user->user_login );
    wp_set_auth_cookie( $id );
    do_action( 'wp_login', $user->user_login );
}

But it is returning this error message:

Warning: Missing argument 2 for wc_maybe_store_user_agent() in plugins/woocommerce/includes/wc-core-functions.php on line 1516

I have tried looking around online but no one seems to have had this issue.


Solution

  • if (!is_user_logged_in()) {
    
        //determine WordPress user account to impersonate
        $user_login = 'guest';
    
        //get user ID
        $user = get_userdatabylogin($user_login); // below WP 3.3.0
    
        //$user =  get_user_by('login', $user_login); above or equals WP 3.3.0
    
        $user_id = $user->ID;
    
        //login
        wp_set_current_user($user_id, $user_login);
        wp_set_auth_cookie($user_id);
        do_action('wp_login', $user_login);
    }
    

    There is a hook in WooCommerce like this.

    add_action( 'wp_login', 'wc_maybe_store_user_agent', 10, 2 );
    

    The "wc_maybe_store_user_agent" expects 2 parameter. If the user ID is not set, it will show the error you mentioned. Test my snippet above

    Function is at line 1516 in plugins/woocommerce/includes/wc-core-functions.php

    function wc_maybe_store_user_agent( $user_login, $user ) {
        if ( 'yes' === get_option( 'woocommerce_allow_tracking', 'no' ) && user_can( $user, 'manage_woocommerce' ) ) {
            $admin_user_agents   = array_filter( (array) get_option( 'woocommerce_tracker_ua', array() ) );
            $admin_user_agents[] = wc_get_user_agent();
            update_option( 'woocommerce_tracker_ua', array_unique( $admin_user_agents ) );
        }
    }
    add_action( 'wp_login', 'wc_maybe_store_user_agent', 10, 2 );