Đôi lúc bạn được yêu cầu viết thêm những sản phẩm đã xem cho theme WordPress đặc biệt là Flatsome. Hôm nay mình giới thiệu tới các bạn cách add short những sản phẩm đã xem nhé!
Mục lục bài viết:
Code sản phẩm đã xem cho theme flatsome wordpress
Chèn code bên dưới vào function.php của theme (ưu tiên child theme nếu có nhé).
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 code trên thì đã xử lý được phần cookie rồi. Tiếp tục là khởi tạo shortcode
Khởi tạo shortcode sản phẩm đã xem
Code sau cũng bỏ vào function.php
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" limit="8" 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();
}
Columns ở dòng số 18 code trên:
- Limit=”8″ có nghĩa là hiển thị tối qua 8 sản phẩm. -> thay số tùy bạn.
- Columns=”6″ số cột là 6. -> thay tù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ị, Sidebar hoặc chỗ nào có thể add html là có thể add shortcode nhé!
[visited_product]
Chúc các bạn thành công!
Bình luận bị cấm: Bình luận có chứa yếu tố SPAM và yếu tố quảng cáo.