原理是访问产品时往浏览器中写入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']");
}
© 版权声明
文章版权归作者所有,未经允许请勿转载。
WWW.ANXKJ.TOP
暂无评论内容