Oshrib Oshrib - 7 months ago 62
PHP Question

Woocommerce session

I have landing page out of my website, with subdomain, lets say:

lp.test.com

On this page i have button "buy" that works great, with the link (example):

http://destination.com/?add-to-cart=10960&mobile=yes

Click on this button - take us to the destination.com cart and add the product to the cart - as i said - it works great.

What I want is to get the previous page url and display it on cart page.
I tried 2 ways: session and query string.

I see the woocommerce is remove any query string so the url is just destination.com/cart , without the string after that.

So I tried sessions:

On the first page i put on first line:

<?php
session_start();
$_SESSION['previous_location'] = 'mobile';
?>


On the second (destination) page, put:

$previous_location = $_SESSION['previous_location'];
echo 'Session: '. $previous_location;


But, it also didn't work. the echo is empty, its print only 'Session: '.

My goal is to recognize if customer came to the cart from external landing page, if he does - i want to display other get_header() of my wordpress.

Answer

(update)

You need to use this code in your function.php file, to test if session_start(); is not used yet by wordpress / woocommerce:

function registering_my_session() {
  if( !session_id() )
    session_start();
}
add_action('init', 'registering_my_session');

So you will only need on the second (destination) page:

<?php
echo 'Session: '. $_SESSION['previous_location'];
?>

This time you will get for $previous_location; ==> mobile


Another way could be to use PHP cookies.

On first page (at the beginning of your php document):

<?php setcookie('previous_location', 'mobile', time() + 365*24*3600), null

, null , false , true); ?>

on second page:

<?php echo $_COOKIE['previous_location']; ?>