hào ACE nha! Hôm nay share code sản phẩm đã xem, với nhiều lựa chọn và phục vụ cho flatsome nói riêng, và tất cả theme wordpress nói chung. Chơi được tất.!
Vào thẳng vấn đề luôn, Theme Computer là Giao diện web đã áp dụng code trên mọi người có thể tham khảo trước!
Set Cookie khi user ghé thăm trang chi tiết sản phẩm
Chèn code bên dưới vào function.php của theme (ưu tiên child theme nếu có nhé).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
function isures_set_user_visited_product_cookie() { if (!is_singular('product')) { return; } global $post; if (empty($_COOKIE['woocommerce_recently_viewed'])) { $viewed_products = array(); } else { $viewed_products = wp_parse_id_list((array) explode('|', wp_unslash($_COOKIE['woocommerce_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) > 22) { array_shift($viewed_products); } wc_setcookie('woocommerce_recently_viewed', implode('|', $viewed_products)); } add_action('wp', 'isures_set_user_visited_product_cookie'); |
Với một ít code trên thì đã xử lý được phần cookie rồi. Tiếp tục là khởi tạo shortcode, đối với Flatsome thì em sẽ ưu tiên thêm 1 lựa chọn khác nữa là tạo thêm 1 element kéo thả vào header trong thời gian tới.
Demo có thể tham khảo trước tại theme wordpress Allin
Khởi tạo shortcode sản phẩm đã xem
Code sau cũng bỏ vào function.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
add_shortcode('isures_recently_viewed_products', 'isures_2718_prod_viewed_atts'); function isures_2718_prod_viewed_atts() { ob_start(); $viewed_products = !empty($_COOKIE['woocommerce_recently_viewed']) ? (array) explode('|', wp_unslash($_COOKIE['woocommerce_recently_viewed'])) : array(); $viewed_products = array_reverse(array_filter(array_map('absint', $viewed_products))); ?> <div id="isures-recently--wrap"> <div class="isures-container"> <?php if (!empty($viewed_products)) { echo do_shortcode('[products type="row" columns="6" ids="' . implode(',', $viewed_products) . '"]'); } else { echo 'Không có sản phẩm xem gần đây'; } ?> </div> </div> <?php return ob_get_clean(); } |
Ở trên mình tận dụng shortcode của woo để kéo ra cho nhanh
Columns ở dòng số 18 code trên – nếu bạn muốn thay đổi số cột sản phẩm thì thay ở đấy.
Hiển thị shortcode sản phẩm đã xem
Tiếp theo để hiển thị được sản phẩm đã xem thì bạn thêm shortcode sau vào nơi cần hiển thị, ví dụ như page!
1 |
[isures_recently_viewed_products] |
Oke như thế là đã xong 1 tính năng sản phẩm đã xem cho website của bạn rồi. Chúc thành công.!
Nguồn: https://thietkewebgiarehcm.com/tao-san-pham-da-xem