简体   繁体   English

为未登录的用户显示最近查看的产品 wordpress

[英]show recently viewed products for non-logged in users wordpress

I'm showing recently viewed products for logged in users with below code, of course before this I'm updating user meta in wp_footer action:我正在使用以下代码为登录用户显示最近查看的产品,当然在此之前我正在 wp_footer 操作中更新用户元数据:

$rv = get_user_meta(get_current_user_id(), 'recently_viewed', true);

But I need to show recently viewed products even when user is not logged in. Is there any way to do it with get_option()/update_option() or in some other way?但是,即使用户未登录,我也需要显示最近查看的产品。有没有办法使用 get_option()/update_option() 或其他方式来做到这一点?

I decided to show recently viewed product list for non-logged in users with cookies.我决定使用 cookie 为未登录的用户显示最近查看的产品列表。 I added below code in my functions.php file and in single product page I'm getting ID values from cookie and using get_post() function to show information:我在我的functions.php文件和单个产品页面中添加了以下代码,我从cookie中获取ID值并使用get_post()函数来显示信息:

function rv_products_non_logged_in(){ 
    $rv_posts = array();
    if ( is_singular('product-items') && !is_user_logged_in()){
        if(isset($_COOKIE['rv_products']) && $_COOKIE['rv_products']!=''){ 
            $rv_posts =  unserialize($_COOKIE['rv_products']);
            if (! is_array($rv_posts)) {
                $rv_posts = array(get_the_ID());
            }else{
                $rv_posts = array_diff($rv_posts, array(get_the_ID()));
                array_unshift($rv_posts,get_the_ID());
            }   
        }else{
            $rv_posts = array(get_the_ID());
        }
        setcookie( 'rv_products', serialize($rv_posts) ,time() + ( DAY_IN_SECONDS * 31 ),'/');
    }
}
add_action('template_redirect', 'rv_products_non_logged_in');

I hope this will help someone else!我希望这会帮助别人!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM