WooCommerce实现商品浏览历史纪录

原理是访问产品时往浏览器中写入Cookies,再通过Cookies存储的产品ID写成短代码展现,最后通过调用短代码实现显示产品。

代码如下,亲测可用:

add_action( 'template_redirect', 'bbloomer_track_product_view', 9999 );
 
function bbloomer_track_product_view() {
   if ( ! is_singular( 'product' ) ) return;
   global $post;
   if ( empty( $_COOKIE['bbloomer_recently_viewed'] ) ) {
      $viewed_products = array();
   } else {
      $viewed_products = wp_parse_id_list( (array) explode( '|', wp_unslash( $_COOKIE['bbloomer_recently_viewed'] ) ) );
   }
   $keys = array_flip( $viewed_products );
   if ( isset( $keys[ $post->ID ] ) ) {
      unset( $viewed_products[ $keys[ $post->ID ] ] );
   }
   $viewed_products[] = $post->ID;
   if ( count( $viewed_products ) > 4 ) {
      array_shift( $viewed_products );
   }
   wc_setcookie( 'bbloomer_recently_viewed', implode( '|', $viewed_products ) );
}
 
add_shortcode( 'recently_viewed_products', 'bbloomer_recently_viewed_shortcode' );
  
function bbloomer_recently_viewed_shortcode() {
   $viewed_products = ! empty( $_COOKIE['bbloomer_recently_viewed'] ) ? (array) explode( '|', wp_unslash( $_COOKIE['bbloomer_recently_viewed'] ) ) : array();
   $viewed_products = array_reverse( array_filter( array_map( 'absint', $viewed_products ) ) );
   if ( empty( $viewed_products ) ) return;
   $title = '<h3">Recently Viewed Products</h3>';
   $product_ids = implode( ",", $viewed_products );
   return $title . do_shortcode("[products ids='$product_ids' orderby='post__in']");
}
© 版权声明
THE END
喜欢就支持一下吧
点赞7 分享
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称常用语 夸夸
夸夸
还有吗!没看够!
表情代码图片

    暂无评论内容