Làm website bán hàng với Woocommerce và những đoạn code cần biết

Làm website bán hàng với Woocommerce và những đoạn code cần biết

1.Cách hiển thị thông tin giảm giá chi tiết và đẹp hơn .

Và đây là những đoạn code mình thấy hay và sưu tập copy từ nhiều nguồn nên mình có để tác giả đoạn code là của ai, nên chủ thớt có đọc được xin dơ cao đánh khẽ mục đích tổng hợp chia sẻ .

 

/*Sale price by devvn - levantoan.com*/
function devvn_price_html($product, $is_variation = false){
ob_start();
if($product->is_on_sale()):
?>
<style>
.devvn_single_price {
background-color: #199bc42e;
border: 1px dashed #199bc4;
padding: 10px;
border-radius: 3px;
-moz-border-radius: 3px;
-webkit-border-radius: 3px;
margin: 0 0 10px;
color: #000;
}
.devvn_single_price span.label {
color: #333;
font-weight: 400;
font-size: 14px;
padding: 0;
margin: 0;
float: left;
width: 82px;
text-align: left;
line-height: 18px;
}
.devvn_single_price span.devvn_price .amount {
font-size: 14px;
font-weight: 700;
color: #ff3a3a;
}
.devvn_single_price span.devvn_price del .amount, .devvn_single_price span.devvn_price del {
font-size: 14px;
color: #333;
font-weight: 400;
}
</style>
<?php
endif;
if($product->is_on_sale() && ($is_variation || $product->is_type('simple') || $product->is_type('external'))) {
$sale_price = $product->get_sale_price();
$regular_price = $product->get_regular_price();
if($regular_price) {
$sale = round(((floatval($regular_price) - floatval($sale_price)) / floatval($regular_price)) * 100);
$sale_amout = $regular_price - $sale_price;
?>
<div class="devvn_single_price">
<div>
<span class="label">Giá:</span>
<span class="devvn_price"><?php echo wc_price($sale_price); ?></span>
</div>
<div>
<span class="label">Thị trường:</span>
<span class="devvn_price"><del><?php echo wc_price($regular_price); ?></del></span>
</div>
<div>
<span class="label">Tiết kiệm:</span>
<span class="devvn_price sale_amount"> <?php echo wc_price($sale_amout); ?> (<?php echo $sale; ?>%)</span>
</div>
</div>
<?php
}
}elseif($product->is_on_sale() && $product->is_type('variable')){
$prices = $product->get_variation_prices( true );
if ( empty( $prices['price'] ) ) {
$price = apply_filters( 'woocommerce_variable_empty_price_html', '', $product );
} else {
$min_price = current( $prices['price'] );
$max_price = end( $prices['price'] );
$min_reg_price = current( $prices['regular_price'] );
$max_reg_price = end( $prices['regular_price'] );
if ( $min_price !== $max_price ) {
$price = wc_format_price_range( $min_price, $max_price ) . $product->get_price_suffix();
} elseif ( $product->is_on_sale() && $min_reg_price === $max_reg_price ) {
$sale = round(((floatval($max_reg_price) - floatval($min_price)) / floatval($max_reg_price)) * 100);
$sale_amout = $max_reg_price - $min_price;
?>
<div class="devvn_single_price">
<div>
<span class="label">Giá:</span>
<span class="devvn_price"><?php echo wc_price($min_price); ?></span>
</div>
<div>
<span class="label">Thị trường:</span>
<span class="devvn_price"><del><?php echo wc_price($max_reg_price); ?></del></span>
</div>
<div>
<span class="label">Tiết kiệm:</span>
<span class="devvn_price sale_amount"> <?php echo wc_price($sale_amout); ?> (<?php echo $sale; ?>%)</span>
</div>
</div>
<?php
} else {
$price = wc_price( $min_price ) . $product->get_price_suffix();
}
}
echo $price;
}else{ ?>
<p class="<?php echo esc_attr( apply_filters( 'woocommerce_product_price_class', 'price' ) );?>"><?php echo $product->get_price_html(); ?></p>
<?php }
return ob_get_clean();
}
function woocommerce_template_single_price(){
global $product;
echo devvn_price_html($product);
}
add_filter('woocommerce_available_variation','devvn_woocommerce_available_variation', 10, 3);
function devvn_woocommerce_available_variation($args, $thisC, $variation){
$old_price_html = $args['price_html'];
if($old_price_html){
$args['price_html'] = devvn_price_html($variation, true);
}
return $args;
}

Code này phù hợp nếu chúng ta đang làm website so sánh, và những code này bạn phải theme vô nếu bạn sài theme flatsome.

2.Tránh spam thôi Xác thực số điện thoại Việt Nam tại trang thanh toán

Chỉ cần copy đoạn code sau vào file functions.php của theme để xác thực số điện thoại gồm 10-11 số và bắt đầu từ số 0 khi thanh toán.

//Nguồn:levantoan.com
add_action('woocommerce_checkout_process', 'devvn_validate_phone_field_process' );
function devvn_validate_phone_field_process() {
    $billing_phone = filter_input(INPUT_POST, 'billing_phone');
    if ( ! (preg_match('/^0([0-9]{9,10})+$/D', $billing_phone )) ){
        wc_add_notice( "Xin nhập đúng <strong>số điện thoại</strong> của bạn"  ,'error' );
    }
}

3.Gắn giỏ hàng minicart bất cứ ở đâu

Bình thường chúng ta chỉ có thêm được ở menu hoặc header hoặc sử dụng elementor để gắn và khi chúng ta thêm sản phẩm vào nó phải loand lại trang nên sẽ lâu đây là cách mà Levantoan.com chia sẻ .

Thêm đoạn code sau vào bất kỹ chỗ nào bạn muốn hiển thị mini cart, có thể chèn vào widget cũng được 

<?php
global $woocommerce;
$cart_url = $woocommerce->cart->get_cart_url();
$cart_items_count = $woocommerce->cart->cart_contents_count;
$cart_total = $woocommerce->cart->get_cart_total();
?>

<a class="cart-contents" href="<?php echo esc_url($cart_url); ?>" title="<?php esc_attr_e('View your shopping cart', 'woothemes'); ?>">
    <?php printf(_n('%d item', '%d items', $cart_items_count, 'woothemes'), $cart_items_count); ?> - <?php echo wp_kses_data($cart_total); ?>
</a>
  1. Escaping URLs và Dữ liệu:
    • Sử dụng esc_url() để escape URL và esc_attr_e() để escape các thuộc tính title.
  2. Sử dụng Biến Tạm Thời:
    • Lưu giữ giá trị của URL, số lượng sản phẩm và tổng giá trị vào các biến tạm thời giúp mã code trở nên dễ đọc hơn.
  3. Sử Dụng wp_kses_data():
    • Sử dụng wp_kses_data() để escape dữ liệu giỏ hàng, giúp đảm bảo rằng nó an toàn khi hiển thị.

Dưới đây là một số vị trí phổ biến bạn có thể chèn mã này:

  1. Header Template:
    • Nếu bạn muốn hiển thị thông tin giỏ hàng ở phần đầu trang của trang web, bạn có thể chèn mã vào file header template của theme. Thường là file header.php hoặc tương tự.
  2. Menu Navigation:
    • Nếu bạn muốn thêm liên kết đến giỏ hàng vào thanh menu, bạn có thể chèn mã này vào một vị trí menu thông qua trình tùy chỉnh menu WordPress.
  3. Widget hoặc Sidebar:
    • Bạn cũng có thể chèn mã này vào một widget hoặc sidebar của WordPress nếu bạn muốn hiển thị nó ở một vị trí khác trên trang.
  4. Elementor hoặc Trình xây dựng trang khác:
    • Nếu bạn sử dụng các trình xây dựng trang như Elementor, bạn có thể thêm một phần tử tùy chỉnh HTML và chèn mã code vào đó.

4.Thay đổi woocommerce mini cart bằng Ajax cập nhật nhanh hơn

Code này chèn vào file functions.php của theme nhé không biết bạn có thể đọc lại bài 1 hướng dẫn .

add_filter('woocommerce_add_to_cart_fragments', 'woocommerce_header_add_to_cart_fragment');
function woocommerce_header_add_to_cart_fragment($fragments) {
    ob_start();
    ?>
    <a class="cart-contents" href="<?php echo esc_url(wc_get_cart_url()); ?>" title="<?php esc_attr_e('View your shopping cart', 'woothemes'); ?>">
        <?php
        echo sprintf(
            _n('%d item', '%d items', WC()->cart->get_cart_contents_count(), 'woothemes'),
            WC()->cart->get_cart_contents_count()
        );
        ?> - <?php echo WC()->cart->get_cart_total(); ?>
    </a>
    <?php
    $fragments['a.cart-contents'] = ob_get_clean();
    return $fragments;
}

5.Thay chữ Sale bằng % trong Woocommerce

/*
* Thay chữ Sale thành phần trăm (%) giảm giá
* Author: levantoan.com
*/
add_filter('woocommerce_sale_flash', 'devvn_woocommerce_sale_flash', 10, 3);
function devvn_woocommerce_sale_flash($html, $post, $product){
return '<span class="onsale"><span>' . devvn_presentage_bubble($product) . '</span></span>';
}
function devvn_presentage_bubble( $product ) {
$post_id = $product->get_id();
if ( $product->is_type( 'simple' ) || $product->is_type( 'external' ) ) {
$regular_price = $product->get_regular_price();
$sale_price = $product->get_sale_price();
$bubble_content = round( ( ( floatval( $regular_price ) - floatval( $sale_price ) ) / floatval( $regular_price ) ) * 100 );
} elseif ( $product->is_type( 'variable' ) ) {
if ( $bubble_content = devvn_percentage_get_cache( $post_id ) ) {
return devvn_percentage_format( $bubble_content );
}
$available_variations = $product->get_available_variations();
$maximumper = 0;
for ( $i = 0; $i < count( $available_variations ); ++ $i ) {
$variation_id = $available_variations[ $i ]['variation_id'];
$variable_product = new WC_Product_Variation( $variation_id );
if ( ! $variable_product->is_on_sale() ) {
continue;
}
$regular_price = $variable_product->get_regular_price();
$sale_price = $variable_product->get_sale_price();
$percentage = round( ( ( floatval( $regular_price ) - floatval( $sale_price ) ) / floatval( $regular_price ) ) * 100 );
if ( $percentage > $maximumper ) {
$maximumper = $percentage;
}
}
$bubble_content = sprintf( __( '%s', 'woocommerce' ), $maximumper );
devvn_percentage_set_cache( $post_id, $bubble_content );
} else {
$bubble_content = __( 'Sale!', 'woocommerce' );
return $bubble_content;
}
return devvn_percentage_format( $bubble_content );
}
function devvn_percentage_get_cache( $post_id ) {
return get_post_meta( $post_id, '_devvn_product_percentage', true );
}
function devvn_percentage_set_cache( $post_id, $bubble_content ) {
update_post_meta( $post_id, '_devvn_product_percentage', $bubble_content );
}
//Định dạng kết quả dạng -{value}%. Ví dụ -20%
function devvn_percentage_format( $value ) {
return str_replace( '{value}', $value, '-{value}%' );
}
// Xóa cache khi sản phẩm hoặc biến thể thay đổi
function devvn_percentage_clear( $object ) {
$post_id = 'variation' === $object->get_type()
? $object->get_parent_id()
: $object->get_id();
delete_post_meta( $post_id, '_devvn_product_percentage' );
}
add_action( 'woocommerce_before_product_object_save', 'devvn_percentage_clear' );

6.Thêm Flash sale và sản phẩm đã bán dưới nút mua hàng

/**
* Hiển thị số lượng sản phẩm đã bán dưới nút "Thêm vào giỏ hàng" trên trang sản phẩm.
*/
function hocwordpress_product_sold_count() {
global $product;
$units_sold = $product->get_total_sales();
if ( $units_sold ) {
$sold_html = '<div class="product-sales epic_box">';
$sold_html .= '<i class="fa fa-shopping-cart"></i>';
$sold_html .= sprintf( __( 'Đã bán: %s', 'woocommerce' ), $units_sold );
$sold_html .= '</div>';
echo $sold_html;
}
}
add_action( 'woocommerce_after_add_to_cart_button', 'hocwordpress_product_sold_count', 10 );
function isures_flashsale_countdown_and_stock_prod()
{
$thepostid = get_the_ID();
$sale_price_dates_to = ($date_to = get_post_meta($thepostid, '_sale_price_dates_to', true)) ? date_i18n('Y-m-d', $date_to) : '';

$sale_from = ($date_from = get_post_meta($thepostid, '_sale_price_dates_from', true)) ? date_i18n('Y-m-d', $date_from) : '';
$strtotime_date_from = strtotime($sale_from);
$strtotime_date_to = strtotime($sale_price_dates_to);
if (!empty($sale_price_dates_to) && $strtotime_date_to > $strtotime_date_from && $strtotime_date_to >= strtotime(date("Y/m/d"))) {
?>

<div class="crazy-deal-details pc">
<div class="crazy-deal-details-right">
<time class="crazy-deal-details-countdown">Kết thúc sau <span data-count="<?php echo $sale_price_dates_to; ?>" id="isures-sale-fl"></span></time>
<?php
global $product;
$stock = $product->get_stock_quantity();
$buy = get_post_meta($product->get_id(), 'total_sales', true);
if (!empty($stock) && $buy > 0) {
$round = round(($buy * 100 / ($stock + $buy)), 0);
?>
<div class="crazy-deal-details-process">
<div class="crazy-deal-details-procressbar">
<div class="crazy-deal-details-procressbar-inner" style="width:<?php echo $round . '%'; ?>"></div>
</div>
<span class="crazy-deal-details-soldtext"><?php echo sprintf(__('Đã bán %s sp', 'woocommerce'), $buy); ?></span>
</div>
<?php
</div>
</div>
<script>
jQuery(function($) {
function updateTimer() {
var isures_count = $("#isures-sale-fl").attr('data-count');
future = Date.parse(isures_count);
now = new Date();
diff = future - now;
days = Math.floor( diff / (1000*60*60*24) );
hours = Math.floor( diff / (1000*60*60) );
mins = Math.floor( diff / (1000*60) );
secs = Math.floor( diff / 1000 );
d = days;
h = hours - days * 24;
m = mins - hours * 60;
s = secs - mins * 60;
$('#isures-sale-fl').html(d + ':' + h + ':' + m + ':' + s);
}
setInterval(function() {
updateTimer();
}, 1000);
});
</script>
<style>
.crazy-deal-details.pc {
margin: 25px auto;
height: 29px;
overflow: hidden;
background-image: url(link hình máy tính );
background-position: 0 0;
background-repeat: no-repeat;
background-size: 100% 100%;
}
.crazy-deal-details-right {
position: relative;
margin-left: 140px;
height: 100%;
display: flex;
align-items: center;
flex-direction: row;
justify-content: space-between;
}
time.crazy-deal-details-countdown {
text-align: left;
font-size: 14px;
}
span#isures-sale-fl {
color: #ff0000;
font-size: 14px;
}
span.crazy-deal-details-soldtext {
color: #f00;
font-size: 12px;
font-weight: bold;
margin-right: 10px;
}
.crazy-deal-details.pc .crazy-deal-details-process {
display: flex;
flex-direction: row-reverse;
align-items: center;
color: #999;
font-weight: 700;
}
.crazy-deal-details.pc .crazy-deal-details-procressbar {
width: 90px;
height: 8px;
background: #ffd1c2;
border-radius: 4px;
display: inline-block;
margin-right: 6px;
margin-left: 6px;
}
.crazy-deal-details.pc .crazy-deal-details-procressbar-inner {
background: linear-gradient(90deg, #ff8763, #ff330c);
border-radius: 4px;
width: 0;
height: 100%;
}
@media screen and (max-width: 1024px) {
.crazy-deal-details.pc {
height: 50px;
background-image: url(link hình điện thoại);
}
.crazy-deal-details-right {
position: relative;
display: flex;
color: #fff;
margin-right: 10px;
height: 100%;
flex-direction: column;
justify-content: center;
align-items: flex-end;
}
.crazy-deal-details-procressbar {
background: hsla(0, 0%, 100%, .5);
}
.crazy-deal-details.pc .crazy-deal-details-procressbar-inner {
background: #fff;
}
.isures-sale-fl,
span.crazy-deal-details-soldtext {
color: #fff !important
}
}
</style>
<?php
}
}
add_action('woocommerce_before_add_to_cart_button', 'isures_flashsale_countdown_and_stock_prod');

Còn đây là đoạn css

.epic_box {
padding-top: 5px;
border: 1px solid #ddd;
padding: 5px;
border-radius: 8px;
margin-bottom:10px;
}
.product-sales{
font-size:15px;
font-weight:600;
}
.product-sales .fa{
margin-right:10px;
}

sau đó các bạn vào trang sản phẩm và chỉnh như thế này là được nhé ! Ak 2 đường link hỉnh ảnh các bạn lấy tải về nhé rồi thay thế nó

Làm Website Bán Hàng Với Woocommerce Và Những đoạn Code Cần Biết
Làm Website Bán Hàng Với Woocommerce Và Những đoạn Code Cần Biết

Bạn có thể tải về nhé

Làm Website Bán Hàng Với Woocommerce Và Những đoạn Code Cần Biết
Làm Website Bán Hàng Với Woocommerce Và Những đoạn Code Cần Biết
Làm Website Bán Hàng Với Woocommerce Và Những đoạn Code Cần Biết
Làm Website Bán Hàng Với Woocommerce Và Những đoạn Code Cần Biết

7.Để giỏ hàng tự động cập nhật khi thay đổi số lượng sản phẩm mà không cần ấn chữ cập nhật giỏ hàng !

Chèn đoạn css này để ẩn nút cập nhật giỏ hàng !

.woocommerce button[name="update_cart"],
.woocommerce input[name="update_cart"] {
	display: none;
}

Sau đó chèn mã này vào file functions.php

add_action( 'wp_footer', 'auto_update_cart' );
function auto_update_cart() {
if ( is_cart() ) :
?>
<script type="text/javascript">
jQuery( function( $ ) {
$('.woocommerce').on( 'change', 'input.qty', function() {
if ( this.value === '' || this.value === '0' ) {
return false;
}
clearTimeout( timeout );
var timeout = setTimeout( function() {
$('[name="update_cart"]').trigger( 'click' );
}, 1000 );
});
});
</script>
<?php
endif;
}

Tổng kết

Trên đây là những mã mình làm mình thấy cần thiết copy từ nhiều nguồn chỉ để cho các bạn tiện theo dõi mà không mất quá nhiều thời gian tìm kiếm và bản thân mình dùng .

Hãy để lại cảm nhận của bạn về bài viết này

Để lại một bình luận

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *

Press ESC to close