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条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度