我用下面的代码显示登录用户最近查看的产品,当然在此之前我在wp_footer action中更新用户元:
$rv = get_user_meta(get_current_user_id(), 'recently_viewed', true);
但是我需要显示最近查看的产品,即使用户没有登录。是否有任何方法可以使用get_option()/update_option()或以其他方式做到这一点?
我决定用cookie为未登录用户显示最近查看的产品列表。我在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');
我希望这将帮助别人!