1. Home
  2. WordPress
  3. How to Set/Unset WooCommerce Session Variables

How to Set/Unset WooCommerce Session Variables

Set/Unset woocommerce session variables

Do you want to know how to set or unset WooCommerce session variables? Generally, we use PHP’s built-in session handler and session_start(). So if you want to create a new session variable in WooCommerce, then you would obviously think of using PHP’s built-in session handler, but you might (at least, I did) land up with few issues. For example, I was developing a plugin for WooCommerce where I created a new session variable using $_SESSION in cart page and read the same in checkout page. But the result was an empty string. The ideal way to set/unset a session variable is to use WooCommerce’s session handler. This tutorial will explain how to Set/Unset WooCommerce session variables.

How to set a Session variable in WooCommerce?

Use WC()->session->set() method to set a session variable.

WC()->session->set('sess_variable_name', $data);

How to read a session variable in WooCommerce?

Use WC()->session->get() method to read a session variable.

WC()->session->get( 'sess_variable_name' );

How to Unset a session variable in WooCommerce?

You can either set a variable to null or just use WC()->session->__unset() method.

WC()->session->set( 'sess_variable_name', null );

(or)

WC()->session->__unset( 'sess_variable_name' );

However, using ‘__unset‘ method will really unset the variable.


Related Content
Updated on September 2, 2017

Was this article helpful?

Related Articles

Add A Comment