Hướng dẫn thêm sản phẩm đã xem vào trang chi tiết sản phẩm
Lưu cookie sản phẩm đã xem
function custom_track_product_view() { if ( ! is_singular( 'product' ) ) { return; } global $post; setPostViews(get_the_ID()); if ( empty( $_COOKIE['woocommerce_recently_viewed'] ) ) $viewed_products = array(); else $viewed_products = (array) explode( '|', $_COOKIE['woocommerce_recently_viewed'] ); if ( ! in_array( $post->ID, $viewed_products ) ) { $viewed_products[] = $post->ID; } if ( sizeof( $viewed_products ) > 15 ) { array_shift( $viewed_products ); } // Store for session only wc_setcookie( 'woocommerce_recently_viewed', implode( '|', $viewed_products ) ); }
Tạo short code hiển thị sản phẩm đã xem
add_shortcode( 'recently_viewed_products', 'recently_viewed_products_func' ); function recently_viewed_products_func() { $viewed_products = ! empty( $_COOKIE['woocommerce_recently_viewed'] ) ? (array) explode( '|', wp_unslash( $_COOKIE['woocommerce_recently_viewed'] ) ) : array(); $viewed_products = array_slice($viewed_products, 0, 8); if ( empty( $viewed_products ) ) return; $title = '<h3 class="product-section-title container-width product-section-title-related pt-half pb-half uppercase">'. __('Recently products') .'</h3>'; $product_ids = implode( ",", $viewed_products ); return '<div class="container">'. $title . do_shortcode("[products ids='$product_ids']") . '</div>'; }
Chèn sản phẩm đã xem vào vị trí bên dưới trang sản phẩm
add_action( ‘woocommerce_after_single_product’, ‘show_viewed_products’, 31 );
function show_viewed_products() {
echodo_shortcode (‘[recently_viewed_products]’);
}