将会话cookie更改为具有到期日期的cookie

WooCommerce creates a cookie called 'woocommerce_recently_viewed' with an array storing all the product id's. By default this cookie is a session cookie however I would like to manipulate this to be 30 days.

What I've tried:

<?php
$viewed_products = $_COOKIE['woocommerce_recently_viewed'];
setcookie('woocommerce_recently_viewed', $viewed_products, strtotime( '+30 days' ), '/');
 ?>

Placing this in the header.php above the html to change the cookie expiry date. This does work once however it somehow reset/breaks the cookie every time after.

Is their anyone so nice trying to push me into the right direction with manipulating this cookie? I've tried looking for a similar problem around here but couldn't find anything related to this.

TL;DR:

Trying to change the expirate date of the cookie 'woocommerce_recently_viewed' cookie. Anybody who can push me into the right direction?

Help would be greatly appreciated.

Thanks / Dylan

Use template_redirect hook with higher priority and set the cookie by using wc_setcookie method.

Something like this:

function wh_overwriteViewedCookieWC()
{
    $viewed_products = [];
    if (empty($_COOKIE['woocommerce_recently_viewed']))
    {
        //cookie not set or empty
    }
    else
    {
        //cookie is set
//      $viewed_products = (array) explode('|', $_COOKIE['woocommerce_recently_viewed']); //<-- get list of product ID

        //your logic to manuplate

        // Store for session only
        wc_setcookie('woocommerce_recently_viewed', implode('|', $viewed_products), strtotime('+30 days')); //<-- see the 3rd param
    }
}

add_action('template_redirect', 'wh_overwriteViewedCookieWC', 99); //<-- high priority

Code goes in functions.php file of your active child theme (or theme). Or also in any plugin php files.
Code is tested and works.

Hope this helps!