Rupak
Rupak

Reputation: 17

WooCommerce WC()->session->get is not getting recognized

We have created a site where a user enters a coupon code and it logs them in by creating a cookie by the name of couponid, then we save that cookie to the WooCommerce session because that cookie actually is the category id from which the products are displayed.

Now sometimes the products get displayed, sometimes not, and whenever our custom cookie is set in the browser and we go to /wp-admin to login, it gives us the following error:

Fatal error: Call to a member function get() on a non-object

The above error on the login screen of WordPress is coming from the following function in our functions.php file:

function gfc_insert_coupon_code_to_session(){

if( 
    is_user_logged_in() 
    || ! array_key_exists( 'couponid', $_COOKIE ) 
    || WC()->session->get( 'couponid', 0 )
){
    return;
}

$couponID = esc_attr( $_COOKIE['couponid'] );

    if( $couponID ){
        WC()->session->set( 'couponid', $couponID );
    }
}

add_action( 'woocommerce_init', 'gfc_insert_coupon_code_to_session' );

Upvotes: 1

Views: 19017

Answers (3)

user4628565
user4628565

Reputation:

Try to use:

WC()->session->set( 'couponid', $couponID );

Before calling:

WC()->session->get( 'couponid', 0 )

Upvotes: 3

Døner M.
Døner M.

Reputation: 353

Test if your are on Back Office, WC()->session isn't set:

if( !is_admin() ) {

Upvotes: 1

Roman Prytkov
Roman Prytkov

Reputation: 83

The if( !is_admin() ) { ... } fix

did the job for me. I changed the email template and if I tried to resend the email from the backend I received this error. So the admin fix was good.

Upvotes: 0

Related Questions