dongqiancui9194 2017-04-10 18:29
浏览 17
已采纳

一个产品页面与其他产品页面的cookie不同

I want to save product id in an array when user opens a product page, and then save that array in a cookie. This is my code:

   if(is_product()) {
       if(isset($_COOKIE['recent'])) {
            $data = unserialize($_COOKIE['recent']);
            $product_id = get_the_ID();
            if(!in_array($product_id, $data)) {
                array_unshift($data, $product_id);
                if(count($data) > 8) {
                    array_pop($data);
                }
                setcookie('recent', serialize($data), time()+(3600*24*7), "/");
            }
            echo "SET";
        }else{
            $data = array();
            $product_id = get_the_ID();
            array_unshift($data, $product_id);
            setcookie('recent', serialize($data), time()+(3600*24*7), "/");
            echo "DIDNT SET";
        }
        print_r($data);
    }

Those echos and print_r is for debugging purposes. So if it is a product page, I check whether cookie is already set, if yes, then I just want to add product ID to the array if it is already there and update the value. And if cookie is not set, I'm creating a new array and then printing content of $data.

The problem is, that all, except one product page works fine. For example I can browse through products and see that it prints out the same array over and over again, but one product page has its own array of IDs, which is array of one element - that product element. That product page has no different URL from others. same pattern: website.com/product/productname/

It seems like it has its own scope. Even tough I used "/" for the domain, so I guess it should be the same across all the website?

What is wrong here?

  • 写回答

2条回答 默认 最新

  • duanguane1670 2017-04-10 22:29
    关注

    I tested this locally and had similar results. The reason you were getting the output errors in your header was because you were trying to set the initial cookie with an integer instead of a string. That and the WP headers were initialized but the query had not fully processed.

    I made a plugin that will run on the template_redirect hook which will allow you to debug much easier. There's also a [recently_viewed] shortcode that'll let you do something with your actual result.

    You can drop this in your theme or create a recently_viewed.php in your plugins folder:

    https://gist.github.com/simplethemes/4f9b6f969bcc0a0a6668aeed75491a15

    /*
    Plugin Name: Set Shop Cookie
    Description: Adds a cookie for most recently viewed products
    Version: 0.1
    Author: Casey Lee
    Author URL: https://simplethemes.com
    */
    
    class SetWpShopCookie {
    
        /**
        *   @var string API URL
        */
        public static $instance;
    
        public $recent_cookie;
        public $cookie_name = 'recent';
        public $recent_products;
    
    
        /** Hook WordPress
        *   @return void
        */
        public function __construct()
        {
            self::$instance = $this;
            add_action( 'template_redirect', array( $this, 'get_recent_cookie') );
            add_action( 'template_redirect', array( $this, 'set_post_cookie') );
            add_shortcode( 'recently_viewed', array( $this, 'recent_products') );
    
        }
    
    
        /**
         * Gets the 'recent' cookie
         * @return array or null
         */
        public function get_recent_cookie()
        {
            $recent_cookie = null;
            $cookies = array();
            foreach ( $_COOKIE as $name => $value ) {
                $cookies[] = new WP_Http_Cookie( array( 'name' => $name, 'value' => $value ) );
            }
            foreach($cookies as $cookie) {
                if ($this->cookie_name == $cookie->name) {
                    $recent_cookie = $cookie;
                    break;
                }
            }
            $this->recent_cookie = $recent_cookie;
        }
    
    
        /**
         * Load scripts when plugin is executed
         * @see  https://developer.wordpress.org/reference/classes/wp_http_cookie/
         */
        public function set_post_cookie()
        {
            global $post;
            $product_id = $post->ID;
            $cookie_time = time() + 60 * 60 * 24 * 7;
    
            // nothing to do here if we're not in a product single
            if (!is_product())
                return;
    
            // create the cookie
            if(!$this->recent_cookie) {
    
                $data = array();
                array_unshift($data, $product_id);
                setcookie($this->cookie_name, serialize($data), $cookie_time, COOKIEPATH, COOKIE_DOMAIN);
    
             // update existing cookie
             } else {
    
                $data = unserialize($this->recent_cookie->value);
                if(!in_array($product_id, $data)) {
                    array_unshift($data, $product_id);
                    if(count($data) > 8) {
                        array_pop($data);
                    }
                    // Use WP globals for portable cookie settings
                    setcookie($this->cookie_name, serialize($data), $cookie_time, COOKIEPATH, COOKIE_DOMAIN);
                }
    
             }
             // Debug
            // var_dump($this->recent_cookie);
    
        }
    
        // Recently viewed products shortcode
        function recent_products( $atts ) {
    
            // Attributes
            $atts = shortcode_atts(
                array(
                    'count' => '5',
                ),
                $atts,
                'recently_viewed'
            );
            $product_data = unserialize($this->recent_cookie->value);
            $str = '';
            if ($product_data) {
                foreach ($product_data as $products_viewed) {
                    $str .= $products_viewed .' ,';
                }
                return 'You recently viewed these products: ' . rtrim($str,',');
            } else {
                return 'Why don\'t you visit our shop?';
            }
    
        }
    }
    new SetWpShopCookie;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容