Adrian
Adrian

Reputation: 3052

How to load woocommerce get_session_cookie on page load in WordPress?

I am checking out an order in WordPress without refreshing the page.

One of the requirements for the one page order without page refresh is for the woocommerce get_session_cookie() to be initialized.

get_session_cookie() is found in class-wc-handler.php file inside it is a class called class WC_Session_Handler extends WC_Session {}

function get_my_wc_session_cookie() {
    WC_Session_Handler::get_session_cookie();
}

add_action('init', 'get_my_wc_session_cookie');

I added the function get_session_cookie() in functions.php and hook it to 'init'

but I am prompted with an error:

Fatal error: Using $this when not in object context in C:\XamppDev\htdocs\mywebsite\wp-content\plugins\woocommerce\includes\class-wc-session-handler.php on line 170

Do you know how can I load get_session_cookie() from woocommerce on page load?

Upvotes: 1

Views: 1503

Answers (2)

Adrian
Adrian

Reputation: 3052

I was able to solve this issue with the code below:

<?php

  WC()->session->set_customer_session_cookie(true);

?>

Upvotes: 0

Virendra Yaduvanshi
Virendra Yaduvanshi

Reputation: 272

My friend try to set the cookie and then get cookie. sometimes at local system woocommerce cookie function desn't give appropriate result.
Please set a cookie by using the function below in functions.php --

<?php
add_action( 'init', 'setting_my_first_cookie' );

function setting_my_first_cookie() {
 setcookie( $v_username, $v_value, 30 * DAY_IN_SECONDS, COOKIEPATH, COOKIE_DOMAIN );
}
?>

Get the Cookie as below --

<?php

if(!isset($_COOKIE[$v_username])) {
  echo "The cookie: '" . $v_username . "' is not set.";
} else {
  echo "The cookie '" . $v_username . "' is set.";
  echo "Cookie is:  " . $_COOKIE[$v_username];
}

?>

Upvotes: 1

Related Questions