Home WordpressWordPress cơ bản Hướng dẫn tùy chỉnh WooCommerce [A-Z]

Hướng dẫn tùy chỉnh WooCommerce [A-Z]

by admincp

Nhắc đến tạo một website bán hàng vừa và nhỏ với wordpress người ta nghĩ ngay đến woocommerce một plugin tạo website thương mại điện tử miễn phí. Bản thân woocommerce cũng đã bao gồm đầy đủ tính năng đáp ứng cho một website bán hàng online, tuy nhiên với nhu cầu sử dụng chúng ta thường cần phải tùy chỉnh woocommerce sao cho phù hợp với nhu cầu của mình.

Bài viết tổng hợp các tuỳ chỉnh Woocommerce cho các bạn yêu mã nguồn WordPress. Không phải là tất cả nhưng cũng đủ dùng và sẽ được tổng hợp dần trong quá trình mình làm việc với WordPress và WooCommerce.

Tùy chỉnh woocommerce bằng plugin

Nếu bạn muốn chỉnh một số tính năng cơ bản của woocommerce như thay đổi text ” sumbit order”, “add to cart”, số lượng sản phẩm trên mỗi trang,… bạn có thể sử dụng plugin woocommerce customizer mà không cần can thiệp code.

Cài đặt tiếng việt cho woocommerce

Nếu bạn đang sử dụng woocommerce tiếng anh và muốn cài đặt tiếng việt cho woocommerce bạn chỉ cần vào Cài đặt -> tổng quan -> chọn ngôn ngữ tiếng việt cho website, sau đó woocommerce sẽ tự động update bản dịch cho bạn.

cài ngôn ngữ cho website

Xem thêm hướng dẫn việt hóa wordpress.

Trình cài đặt Wizard của woocommerce

Chức năng này giúp cài đặt tình tự các thành phần quan trọng của woocommerce ( trang giỏ hàng, thanh toán, tài khoản,…) Khi lần đầu cài đặt plugin woocommerce bạn sẽ thấy thông báo của trình cài đặt wizard tuy nhiên nếu bạn lỡ bỏ qua thông báo và muốn quay lại trình cài đặt Wizard một lần nữa để cấu hình bạn có thế tìm thấy nó tại Woocommerce -> cài đặt -> Trợ giúp.

wizard wocommerce

Shortcode – Show sản phẩm ra ngoài trang chủ ( hoặc trang bất kì )

Để hiển thị sản phẩm woocommerce ra ngoài trang chủ hay một trang bất kì bạn chỉ cần sử dụng các shortcode như sau:

//Show sản phẩm mới nhất
[recent_ products per_page="12" columns="4"]

//Show sản phẩm nổi bật:
[featured_ products per_page="12" columns="4"]

//Show sản phẩm theo ID:
[product id = '1']

//Show sản phẩm theo nhiều ID:
[products ids="1, 2, 3, 4, 5"]

//Show sản phẩm đang giảm giá:
[sale_products per_page="12"]

//Show sản phẩm bán chạy:
[best_selling_products per_page="12"]

//Show sản phẩm theo danh mục:
[product_category category="SEO"]

Nếu bạn muốn đưa trang shop ra ngoài trang chủ thì bạn setup như hình bên dưới:

cài shop ra trang chủ

Hiển thị “chỉ từ: xxxx” thay vì giá xxx – yyy

tùy biến giá xx-yy

Chèn vào file functions.php của theme / child theme.

add_filter( 'woocommerce_variable_price_html', 'variation_price_format_min', 9999, 2 );
  
function variation_price_format_min( $price, $product ) {
   $prices = $product->get_variation_prices( true );
   $min_price = current( $prices['price'] );
   $price = sprintf( __( 'Chỉ từ: %1$s', 'woocommerce' ), wc_price( $min_price ) );
   return $price;
}

Thay đổi text “add to cart ” hoặc “thêm vào giỏ”

Để thay đổi văn bản mặc định add to cart của woocommerce thành call to action bạn muốn bạn có thể chèn đoạn code sau vào file functions.php

/*
 * Thay đổi nội dung nút Add to Cart
*/
add_filter('woocommerce_product_single_add_to_cart_text', 'woo_custom_cart_button_text');
 
function woo_custom_cart_button_text() {
return __('Book Now', 'woocommerce');
}

Ẩn thông tin hiển thị số lượng, sắp xếp trong trang cửa hàng, danh mục sản phẩm

Truy cập vào Admin > Appearance > Customize > Additional CSS. Thêm đoạn code CSS vào rồi lưu lại.

.woocommerce-result-count.woocommerce-ordering, .woocommerce-ordering select {
    display: none;
}

Ẩn hoặc Thay đổi tiêu đề trong (mô tả sản phẩm, tab đánh giá..)

Bạn muốn xóa dòng bên dưới ?

Sử dụng đoạn code sau:

// Remove the product description Title
add_filter( 'woocommerce_product_description_heading', 'remove_product_description_heading' );
function remove_product_description_heading() {
 return '';
}
 
// Change the product description title
add_filter('woocommerce_product_description_heading', 'change_product_description_heading');
function change_product_description_heading() {
 return __('NEW TITLE HERE', 'woocommerce');
}

Có thể áp dụng với các tab khác như Đánh giá, thông tin bổ sung. Ví dụ:

// Remove on single product panel 'Additional Information' since it already says it on tab.
add_filter('woocommerce_product_additional_information_heading', 'remove_product_additional_information_heading'); 
function remove_product_additional_information_heading() {
 echo '';
 /*return ''; */
}

Xem thêm: https://docs.woocommerce.com/document/editing-product-data-tabs/

Xóa tab đánh giá trong woocommerce

Nếu bạn cho rằng tab review không cần thiết với bạn thì bạn có thể ẩn nó đi bằng cách thêm đoạn code sau.

add_filter( 'woocommerce_product_tabs', 'wcs_woo_remove_reviews_tab', 98 );

function wcs_woo_remove_reviews_tab( $tabs ) {
	unset( $tabs['reviews'] ); // Remove the reviews tab

	return $tabs;
}

Xem thêm Tùy chỉnh tabs sản phẩm cho WooCommerce.

Thêm đoạn text tùy chỉnh bên dưới tiêu đề sản phẩm

Trong mỗi trang chi tiết sản phẩm nếu bạn muốn thêm một đoạn text tùy chỉnh luôn xuất hiện bên dưới tiêu đề sản phẩm thì chỉ cần dùng đoạn code sau:

function hoangweb_magik_custom_text( $post_excerpt ) 
{
      $content="đoạn văn bản tùy chỉnh";
       return $content.'<br>'.$post_excerpt;
}
add_filter('woocommerce_short_description', 'hoangweb_magik_custom_text', 10, 1);

Ẩn sản phẩm woocommerce từ một danh mục cụ thể trên trang cửa hàng

Mặc định trên trang Shop của woocommerce sẽ hiển thị tất cả các sản phẩm, tuy nhiên nếu bạn muốn ẩn tất cả sản phẩm thuộc một danh mục nào đó, sử dụng đoạn code dưới đây.

/**
 * ẩn tất cả sản phẩm của danh mục ( id danh mục )
 */

add_action( 'pre_get_posts', 'hoangweb_remove_product_cats_shop_page');

function hoangweb_remove_product_cats_shop_page( $qry ) {

	// Chú ý thay thông tin của bạn ở các trường bên dưới
	if ( is_admin() ) return;
	
	if ( is_shop() && $qry->is_main_query() ) {
 
		$qry->set( 'tax_query', array(
			array(
				'taxonomy' => 'product_cat',
				'field' => 'ID',
				'terms' => array( 93),
				'operator' => 'NOT IN'
			)
		) );
	
	}
 
}

Thêm thông tin trước và sau GIÁ sản phẩm

Xem tại đây.

Hiển thị GIÁ + GIÁ THƯỜNG + TIỀN TIẾT KIỆM

Thêm đoạn code sau vào functions.php

/*Sale price by - hoangweb.com*/
function hoangweb_price_html($product, $is_variation = false){
    ob_start();
    if($product->is_on_sale() && ($product->is_type( 'simple' ) || $product->is_type( 'external' ) || $is_variation) ) {
        $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;
            ?>
            <style>
                .hoangweb_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;
                }
 
                .hoangweb_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;
                }
 
                .hoangweb_single_price span.hoangweb_price .amount {
                    font-size: 14px;
                    font-weight: 700;
                    color: #ff3a3a;
                }
 
                .hoangweb_single_price span.hoangweb_price del .amount, .hoangweb_single_price span.hoangweb_price del {
                    font-size: 14px;
                    color: #333;
                    font-weight: 400;
                }
            </style>
            <div class="hoangweb_single_price">
                <div>
                    <span class="label">Giá:</span>
                    <span class="hoangweb_price"><?php echo wc_price($sale_price); ?></span>
                </div>
                <div>
                    <span class="label">Thị trường:</span>
                    <span class="hoangweb_price"><del><?php echo wc_price($regular_price); ?></del></span>
                </div>
                <div>
                    <span class="label">Tiết kiệm:</span>
                    <span class="hoangweb_price sale_amount"> <?php echo wc_price($sale_amout); ?> (<?php echo $sale; ?>%)</span>
                </div>
            </div>
            <?php
        }
    }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 hoangweb_price_html($product);
}
 
add_filter('woocommerce_available_variation','hoangweb_woocommerce_available_variation', 10, 3);
function hoangweb_woocommerce_available_variation($args, $thisC, $variation){
    $old_price_html = $args['price_html'];
    if($old_price_html){
        $args['price_html'] = hoangweb_price_html($variation, true);
    }
    return $args;
}
?>

Thêm nút “Mua ngay” “Buy Now” cạnh nút “Thêm vào giỏ hàng”

Có 2 cách để làm điều này.

Cách 1:

add_action('woocommerce_after_add_to_cart_button','hoangweb_quickbuy_after_addtocart_button');
 function hoangweb_quickbuy_after_addtocart_button(){
     global $product;
     global $post;
     ?>
     <div class="custorm_quickbuy"><a href="?quick_buy=1&add-to-cart=<?php echo $post->ID ;?>" class="qn_btn">Mua ngay</a></div>
 
   <?php endif;?>
}

Cách 2: Mở file functions.php trong theme hoặc child theme của bạn đang sử dụng.

/*
 * Add quickbuy button go to checkout after click
 * Author: hoangweb.com
 */
add_action('woocommerce_after_add_to_cart_button','hoangweb_quickbuy_after_addtocart_button');
function hoangweb_quickbuy_after_addtocart_button(){
    global $product;
    ?>
    <button type="submit" name="add-to-cart" value="<?php echo esc_attr($product->get_id()); ?>" class="single_add_to_cart_button button alt" id="buy_now_button">
        <?php _e('Mua ngay', 'devvn'); ?>
    </button>
    <input type="hidden" name="is_buy_now" id="is_buy_now" value="0" />
    <script>
        jQuery(document).ready(function(){
            jQuery('body').on('click', '#buy_now_button', function(){
                if(jQuery(this).hasClass('disabled')) return;
                var thisParent = jQuery(this).closest('form.cart');
                jQuery('#is_buy_now', thisParent).val('1');
                thisParent.submit();
            });
        });
    </script>
    <?php
}
add_filter('woocommerce_add_to_cart_redirect', 'redirect_to_checkout');
function redirect_to_checkout($redirect_url) {
    if (isset($_REQUEST['is_buy_now']) && $_REQUEST['is_buy_now']) {
        $redirect_url = wc_get_checkout_url();
    }
    return $redirect_url;
}
?>

Đoạn trên sau khi click vào nút Mua Ngay sẽ chuyển hướng tới trang thanh toán. Nếu bạn nào muốn chuyển hướng tới trang giỏ hàng thì sửa dòng 28 : từ $redirect_url = wc_get_checkout_url(); thành $redirect_url = wc_get_cart_url(); . Lưu ý: Code này đã được test với biến thể mặc định của woo.

Thay đổi sản phẩm 0đ thành “Liên hệ”

Thêm code sau vào file functions.php của theme đang kích hoạt.

Cách 1: chuyển 0đ thành chữ “Liên hệ”.

function hoangweb_wc_custom_get_price_html( $price, $product ) {
    if ( $product->get_price() == 0 ) {
        if ( $product->is_on_sale() && $product->get_regular_price() ) {
            $regular_price = wc_get_price_to_display( $product, array( 'qty' => 1, 'price' => $product->get_regular_price() ) );
 
            $price = wc_format_price_range( $regular_price, __( 'Free!', 'woocommerce' ) );
        } else {
            $price="" . __( 'Liên hệ', 'woocommerce' ) . '';
        }
    }
    return $price;
}
add_filter( 'woocommerce_get_price_html', 'hoangweb_wc_custom_get_price_html', 10, 2 );

Cách 2: Chuyển giá thành “Liên hệ” khi hết hàng

function hoangweb_oft_custom_get_price_html( $price, $product ) {
    if ( !is_admin() && !$product->is_in_stock()) {
       $price="" . __( 'Liên hệ', 'woocommerce' ) . '';
    }
    return $price;
}
add_filter( 'woocommerce_get_price_html', 'hoangweb_oft_custom_get_price_html', 99, 2 );

Thu gọn, ẩn bớt nội dung mô tả CHI TIẾT sản phẩm Woocommerce

Chúng ta mở file function.php của theme hoặc child theme đang sử dụng, và thêm vào đoạn code này. Lưu ý: code chỉ hoạt động với flatsome themes.

Tạo nút “xem thêm”

/*
* Author: Vinastar - https://vinastar.net
*/
add_action('wp_footer','hoangweb_readmore_flatsome');
function hoangweb_readmore_flatsome(){
    ?>
    <style>
        .single-product div#tab-description {
            overflow: hidden;
            position: relative;
        }
        .single-product .tab-panels div#tab-description.panel:not(.active) {
            height: 0 !important;
        }
        .hoangweb_readmore_flatsome {
            text-align: center;
            cursor: pointer;
            position: absolute;
            z-index: 9999;
            bottom: 0;
            width: 100%;
            background: #fff;
        }
        .hoangweb_readmore_flatsome:before {
            height: 55px;
            margin-top: -45px;
            content: -webkit-gradient(linear,0% 100%,0% 0%,from(#fff),color-stop(.2,#fff),to(rgba(255,255,255,0)));
            display: block;
        }
        .hoangweb_readmore_flatsome a {
            color: #318A00;
            display: block;
        }
        .hoangweb_readmore_flatsome a:after {
            content: '';
            width: 0;
            right: 0;
            border-top: 6px solid #318A00;
            border-left: 6px solid transparent;
            border-right: 6px solid transparent;
            display: inline-block;
            vertical-align: middle;
            margin: -2px 0 0 5px;
        }
    </style>
    <script>
        (function($){
            $(document).ready(function(){
                $(window).load(function(){
                    if($('.single-product div#tab-description').length > 0){
                        var wrap = $('.single-product div#tab-description');
                        var current_height = wrap.height();
                        var your_height = 300;
                        if(current_height > your_height){
                            wrap.css('height', your_height+'px');
                            wrap.append(function(){
                                return '<div class="hoangweb_readmore_flatsome"><a title="Xem thêm" href="javascript:void(0);">Xem thêm</a></div>';
                            });
                            $('body').on('click','.hoangweb_readmore_flatsome', function(){
                                wrap.removeAttr('style');
                                $('body .hoangweb_readmore_flatsome').remove();
                            });
                        }
                    }
                });
            })
        })(jQuery)
    </script>
    <?php
}
?>

Tạo nút “xem thêm” + “Thu gọn”.

/*
* Author: Vinastar - https://vinastar.net
* Đoạn code thu gọn nội dung bao gồm cả nút xem thêm và thu gọn lại sau khi đã click vào xem thêm
*/
add_action('wp_footer','hoangweb_readmore_flatsome');
function hoangweb_readmore_flatsome(){
    ?>
    <style>
        .single-product div#tab-description {
            overflow: hidden;
            position: relative;
            padding-bottom: 25px;
        }
        .single-product .tab-panels div#tab-description.panel:not(.active) {
            height: 0 !important;
        }
        .hoangweb_readmore_flatsome {
            text-align: center;
            cursor: pointer;
            position: absolute;
            z-index: 10;
            bottom: 0;
            width: 100%;
            background: #fff;
        }
        .hoangweb_readmore_flatsome:before {
            height: 55px;
            margin-top: -45px;
            content: -webkit-gradient(linear,0% 100%,0% 0%,from(#fff),color-stop(.2,#fff),to(rgba(255,255,255,0)));
            display: block;
        }
        .hoangweb_readmore_flatsome a {
            color: #318A00;
            display: block;
        }
        .hoangweb_readmore_flatsome a:after {
            content: '';
            width: 0;
            right: 0;
            border-top: 6px solid #318A00;
            border-left: 6px solid transparent;
            border-right: 6px solid transparent;
            display: inline-block;
            vertical-align: middle;
            margin: -2px 0 0 5px;
        }
        .hoangweb_readmore_flatsome_less a:after {
            border-top: 0;
            border-left: 6px solid transparent;
            border-right: 6px solid transparent;
            border-bottom: 6px solid #318A00;
        }
        .hoangweb_readmore_flatsome_less:before {
            display: none;
        }
    </style>
    <script>
        (function($){
            $(document).ready(function(){
                $(window).load(function(){
                    if($('.single-product div#tab-description').length > 0){
                        var wrap = $('.single-product div#tab-description');
                        var current_height = wrap.height();
                        var your_height = 300;
                        if(current_height > your_height){
                            wrap.css('height', your_height+'px');
                            wrap.append(function(){
                                return '<div class="hoangweb_readmore_flatsome hoangweb_readmore_flatsome_more"><a title="Xem thêm" href="javascript:void(0);">Xem thêm</a></div>';
                            });
                            wrap.append(function(){
                                return '<div class="hoangweb_readmore_flatsome hoangweb_readmore_flatsome_less" style="display: none;"><a title="Xem thêm" href="javascript:void(0);">Thu gọn</a></div>';
                            });
                            $('body').on('click','.hoangweb_readmore_flatsome_more', function(){
                                wrap.removeAttr('style');
                                $('body .hoangweb_readmore_flatsome_more').hide();
                                $('body .hoangweb_readmore_flatsome_less').show();
                            });
                            $('body').on('click','.hoangweb_readmore_flatsome_less', function(){
                                wrap.css('height', your_height+'px');
                                $('body .hoangweb_readmore_flatsome_less').hide();
                                $('body .hoangweb_readmore_flatsome_more').show();
                            });
                        }
                    }
                });
            })
        })(jQuery)
    </script>
    <?php
}
?>

Thu gọn, ẩn bớt nội dung mô tả DANH MỤC sản phẩm

Giống như trên, bạn cũng muốn thu gọn nội dung mô tả danh mục sản phẩm. Chú ý: code chỉ hoạt động với theme flatsome.

/*
 * Thêm nút Xem thêm vào phần mô tả của danh mục sản phẩm
 * Author: Vinastar - https://vinastar.net
*/
add_action('wp_footer','hoangweb_readmore_taxonomy_flatsome');
function hoangweb_readmore_taxonomy_flatsome(){
    if(is_woocommerce() && is_tax('product_cat')):
        ?>
        <style>
            .tax-product_cat.woocommerce .shop-container .term-description {
                overflow: hidden;
                position: relative;
                margin-bottom: 20px;
                padding-bottom: 25px;
            }
            .hoangweb_readmore_taxonomy_flatsome {
                text-align: center;
                cursor: pointer;
                position: absolute;
                z-index: 10;
                bottom: 0;
                width: 100%;
                background: #fff;
            }
            .hoangweb_readmore_taxonomy_flatsome:before {
                height: 55px;
                margin-top: -45px;
                content: -webkit-gradient(linear,0% 100%,0% 0%,from(#fff),color-stop(.2,#fff),to(rgba(255,255,255,0)));
                display: block;
            }
            .hoangweb_readmore_taxonomy_flatsome a {
                color: #318A00;
                display: block;
            }
            .hoangweb_readmore_taxonomy_flatsome a:after {
                content: '';
                width: 0;
                right: 0;
                border-top: 6px solid #318A00;
                border-left: 6px solid transparent;
                border-right: 6px solid transparent;
                display: inline-block;
                vertical-align: middle;
                margin: -2px 0 0 5px;
            }
            .hoangweb_readmore_taxonomy_flatsome_less:before {
                display: none;
            }
            .hoangweb_readmore_taxonomy_flatsome_less a:after {
                border-top: 0;
                border-left: 6px solid transparent;
                border-right: 6px solid transparent;
                border-bottom: 6px solid #318A00;
            }
        </style>
        <script>
            (function($){
                $(document).ready(function(){
                    $(window).load(function(){
                        if($('.tax-product_cat.woocommerce .shop-container .term-description').length > 0){
                            var wrap = $('.tax-product_cat.woocommerce .shop-container .term-description');
                            var current_height = wrap.height();
                            var your_height = 300;
                            if(current_height > your_height){
                                wrap.css('height', your_height+'px');
                                wrap.append(function(){
                                    return '<div class="hoangweb_readmore_taxonomy_flatsome hoangweb_readmore_taxonomy_flatsome_show"><a title="Xem thêm" href="javascript:void(0);">Xem thêm</a></div>';
                                });
                                wrap.append(function(){
                                    return '<div class="hoangweb_readmore_taxonomy_flatsome hoangweb_readmore_taxonomy_flatsome_less" style="display: none"><a title="Thu gọn" href="javascript:void(0);">Thu gọn</a></div>';
                                });
                                $('body').on('click','.hoangweb_readmore_taxonomy_flatsome_show', function(){
                                    wrap.removeAttr('style');
                                    $('body .hoangweb_readmore_taxonomy_flatsome_show').hide();
                                    $('body .hoangweb_readmore_taxonomy_flatsome_less').show();
                                });
                                $('body').on('click','.hoangweb_readmore_taxonomy_flatsome_less', function(){
                                    wrap.css('height', your_height+'px');
                                    $('body .hoangweb_readmore_taxonomy_flatsome_show').show();
                                    $('body .hoangweb_readmore_taxonomy_flatsome_less').hide();
                                });
                            }
                        }
                    });
                })
            })(jQuery)
        </script>
    <?php
    endif;
}
?>

Tại dòng 63 có giá trị là 300, đây là chiều cao của khung mô tả sản phẩm. Hãy thay đổi giá trị đó cho phù hợp.

Tạo trang dõi đơn hàng qua email

Tính năng này đã có sẵn trong plugin Woocommerce rồi, để sử dụng hãy tạo một trang và dán đoạn shortcode vào là OK.

[woocommerce_order_tracking]

Thay icon xoá sản phẩm ở giỏ hàng

Chỉ đơn giản Dán đoạn code css bên dưới vào CSS bổ sung của theme đang kích hoạt.

.woocommerce a.remove {
    width: 30px;
    height: 22px;
    position: relative;
    transition: opacity 200ms;
    vertical-align: top;
    display: block;
    -webkit-appearance: none;
    background: none;
    border: none;
    cursor: pointer;
    outline: none;
    padding: 0;
    text-indent: -9999px;
}
.woocommerce a.remove:before, .woocommerce a.remove:after {
    background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA4AAAAQCAQAAACMnYaxAAAAXUlEQVR4XsWQQQrAQAgD84Pti/JSoaftN1MCdgXxXgYvGfUQyABE4DEIUJmeuKgVlJI5em0RGTesFXXZuLwCzvL2pYbHmfCTNSXxpyyajLGClFy7K1dgaaho7YYovIpO3rju6hYFAAAAAElFTkSuQmCC) 0 0 no-repeat;
    left: 8px;
    position: absolute;
    right: 8px;
    top: 2px;
    display: inline-block;
    content: '';
}
.woocommerce a.remove:before{
    height: 6px;
    transform-origin: -7% 100%;
    -moz-transform-origin: -7% 100%;
    -webkit-transform-origin: -7% 100%;
    transition: transform 150ms;
    -moz-transition: transform 150ms;
    -webkit-transition: transform 150ms;
    width: 14px;
}
.woocommerce a.remove:after{
    background-position: -1px -4px;
    height: 12px;
    margin-left: 1px;
    margin-right: 2px;
    margin-top: 4px;
    width: 11px;
}
.woocommerce a.remove:hover:before{
    transform: rotate(-45deg);
    -moz-transform: rotate(-45deg);
    -webkit-transform: rotate(-45deg);
    transition: transform 250ms;
    -moz-transition: transform 250ms;
    -webkit-transition: transform 250ms;
}
.woocommerce a.remove:hover {
    background: transparent;
}

Thêm yêu cầu xuất hoá đơn VAT

Đối với khách hàng là công ty họ sẽ cần xuất hóa đơn VAT. Và khi đó bạn cần lấy thông tin như tên công ty, mã số thuế, ..Chúng ta sẽ thêm các trường này ở trang thanh toán WooCommerce. Thực hiện code theo các bước sau:

Bước 1: Thêm trường xuất VAT cho form thanh toán

/*
 * Thêm lựa chọn xuất hóa đơn VAT vào checkout
 * Author: https://vinastar.net
 * */
add_action('woocommerce_after_checkout_billing_form','hoangweb_xuat_hoa_don_vat');
function hoangweb_xuat_hoa_don_vat(){
    ?>
    <style>
        .hoangweb_xuat_hoa_don_do {
            background: #eee;
            padding: 10px;
            border-radius: 3px;
        }
        .hoangweb_xuat_vat_wrap {
            display: none;
        }
        label.hoangweb_xuat_vat_input_label {
            display: block;
            cursor: pointer;
            margin-bottom: 0;
        }
        .hoangweb_xuat_vat_wrap fieldset {
            margin: 10px 0;
            padding: 10px;
            background: transparent;
            border: 1px solid #b0aeae;
        }
        .hoangweb_xuat_vat_wrap fieldset legend {
            background: transparent;
            padding: 0 5px;
            margin: 0 0 0 10px;
            font-size: 14px;
            display: inline;
            width: inherit;
            border: 0;
            text-transform: none;
            color: #000;
        }
        .hoangweb_xuat_vat_wrap fieldset p {
            margin-bottom: 10px;
        }
        .hoangweb_xuat_vat_wrap fieldset p:last-child {
            margin-bottom: 0;
        }
        .vat_active .hoangweb_xuat_vat_wrap {
            display: block;
        }
    </style>
    <div class="hoangweb_xuat_hoa_don_do">
        <label class="hoangweb_xuat_vat_input_label">
            <input class="hoangweb_xuat_vat_input" type="checkbox" name="hoangweb_xuat_vat_input" value="1">
            Xuất hóa đơn VAT
        </label>
        <div class="hoangweb_xuat_vat_wrap">
            <fieldset>
                <legend>Thông tin xuất hóa đơn:</legend>
                <p class="form-row form-row-first" id="billing_vat_company_field">
                    <label for="billing_vat_company" class="">Tên công ty <abbr class="required" title="bắt buộc">*</abbr></label>
                    <input type="text" class="input-text " name="billing_vat_company" id="billing_vat_company" placeholder="" value="">
                </p>
                <p class="form-row form-row-last" id="billing_vat_mst_field">
                    <label for="billing_vat_mst" class="">Mã số thuế <abbr class="required" title="bắt buộc">*</abbr></label>
                    <input type="text" class="input-text " name="billing_vat_mst" id="billing_vat_mst" placeholder="" value="">
                </p>
                <p class="form-row form-row-wide " id="billing_vat_companyaddress_field">
                    <label for="billing_vat_companyaddress" class="">Địa chỉ <abbr class="required" title="bắt buộc">*</abbr></label>
                    <span class="woocommerce-input-wrapper"><input type="text" class="input-text " name="billing_vat_companyaddress" id="billing_vat_companyaddress" placeholder="" value=""></span>
                </p>
            </fieldset>
        </div>
    </div>
    <script type="text/javascript">
        (function ($) {
            $(document).ready(function () {
                function check_vat(){
                    var parentVAT = $('input.hoangweb_xuat_vat_input').closest('.hoangweb_xuat_hoa_don_do');
                    if($('input.hoangweb_xuat_vat_input').is(":checked")){
                        parentVAT.addClass('vat_active');
                    }else{
                        parentVAT.removeClass('vat_active');
                    }
                }
                check_vat();
                $('input.hoangweb_xuat_vat_input').on('change', function () {
                    check_vat();
                });
            });
        })(jQuery);
    </script>
    <?php
}
?>

Bước 2: Xác nhận dữ liệu khách nhập vào đã đủ hay chưa.

add_action('woocommerce_checkout_process', 'vat_checkout_field_process');
function vat_checkout_field_process()
{
    if (isset($_POST['hoangweb_xuat_vat_input']) && !empty($_POST['hoangweb_xuat_vat_input'])) {
        if (empty($_POST['billing_vat_company'])) {
            wc_add_notice(__('Hãy nhập tên công ty') , 'error');
        }
        if (empty($_POST['billing_vat_mst'])) {
            wc_add_notice(__('Hãy nhập mã số thuế') , 'error');
        }
        if (empty($_POST['billing_vat_companyaddress'])) {
            wc_add_notice(__('Hãy nhập địa chỉ công ty') , 'error');
        }
    }
}

Bước 3: Lưu các giá trị khách nhập vào đơn hàng

add_action('woocommerce_checkout_update_order_meta', 'vat_checkout_field_update_order_meta');
function vat_checkout_field_update_order_meta($order_id)
{
    if (isset($_POST['hoangweb_xuat_vat_input']) && !empty($_POST['hoangweb_xuat_vat_input'])) {
        update_post_meta($order_id, 'hoangweb_xuat_vat_input', intval($_POST['hoangweb_xuat_vat_input']));
        if (isset($_POST['billing_vat_company']) && !empty($_POST['billing_vat_company'])) {
            update_post_meta($order_id, 'billing_vat_company', sanitize_text_field($_POST['billing_vat_company']));
        }
        if (isset($_POST['billing_vat_mst']) && !empty($_POST['billing_vat_mst'])) {
            update_post_meta($order_id, 'billing_vat_mst', sanitize_text_field($_POST['billing_vat_mst']));
        }
        if (isset($_POST['billing_vat_companyaddress']) && !empty($_POST['billing_vat_companyaddress'])) {
            update_post_meta($order_id, 'billing_vat_companyaddress', sanitize_text_field($_POST['billing_vat_companyaddress']));
        }
    }
}

Bước 4: Hiển thị thông tin VAT trong đơn hàng

add_action( 'woocommerce_admin_order_data_after_shipping_address', 'hoangweb_after_shipping_address_vat', 99);
function hoangweb_after_shipping_address_vat($order){
    $hoangweb_xuat_vat_input = get_post_meta($order->get_id(), 'hoangweb_xuat_vat_input', true);
    $billing_vat_company = get_post_meta($order->get_id(), 'billing_vat_company', true);
    $billing_vat_mst = get_post_meta($order->get_id(), 'billing_vat_mst', true);
    $billing_vat_companyaddress = get_post_meta($order->get_id(), 'billing_vat_companyaddress', true);
    ?>
    <p><strong>Xuất hóa đơn:</strong> <?php echo ($hoangweb_xuat_vat_input) ? 'Có' : 'Không';?></p>
    <?php
    if($hoangweb_xuat_vat_input):
        ?>
        <p>
            <strong>Thông tin xuất hóa đơn:</strong><br>
            Tên công ty: <?php echo $billing_vat_company;?><br>
            Mã số thuế: <?php echo $billing_vat_mst;?><br>
            Địa chỉ: <?php echo $billing_vat_companyaddress;?><br>
        </p>
    <?php
    endif;
}
?>

Thêm trường xác thực địa chỉ email trong trang thanh toán (checkout)

/*Xác nhận Email khi checkout*/
// Add second email address field to checkout
add_filter( 'woocommerce_checkout_fields' , 'add_checkout_field' );
function add_checkout_field( $fields = array() ) {
 $fields['billing']['billing_email-2'] = array(
 'label' => __( 'Confirm Email Address', 'wc_emailvalidation' ),
 'placeholder' => _x( 'Email Address', 'placeholder', 'wc_emailvalidation' ),
 'required' => true,
 'class' => apply_filters( 'woocommerce_confirm_email_field_class', array( 'form-row-first' ) ),
 'clear' => true,
 'validate' => array( 'email' ),
 );
 return $fields;
}
// Add default value to second email address field (for WC 2.2+)
add_filter( 'default_checkout_billing_email-2', 'default_field_value' , 10, 2 );
function default_field_value( $value = null, $field = 'billing_email-2' ) {
 if ( is_user_logged_in() ) {
 global $current_user;
 $value = $current_user->user_email;
 }
 return $value;
}
// Ensure email addresses match
add_filter( 'woocommerce_process_checkout_field_billing_email-2' , 'validate_email_address' );
function validate_email_address( $confirm_email="" ) {
 global $woocommerce;
 
 $billing_email = $woocommerce->checkout->posted['billing_email'];
 
 if( strtolower( $confirm_email ) != strtolower( $billing_email ) ) {
 
 $notice = sprintf( __( '%1$sEmail addresses%2$s do not match.' , 'wc_emailvalidation' ) , '<strong>' , '</strong>' );
 
 if ( version_compare( WC_VERSION, '2.3', '<' ) ) {
 $woocommerce->add_error( $notice );
 } else {
 wc_add_notice( $notice, 'error' );
 }
 
 }
 
 return $confirm_email;
}

Cho phép nhập số thập phân trong ô số lượng của woocommerce

Một số mặt hàng có thể đếm số lượng bằng số thập phân. Để kích hoạt cho phép điền số thập phân, chúng ta sử dụng đoạn code sau:

// Simple products
add_filter( 'woocommerce_quantity_input_args', 'hoangweb_woocommerce_quantity_input_args', 10, 2 );
function hoangweb_woocommerce_quantity_input_args( $args, $product ) {
    if ( is_singular( 'product' ) ) {
        $args['input_value']   = 1; // Starting value (we only want to affect product pages, not cart)
    }
    $args['max_value']     = 80;  // Maximum value
    $args['min_value']     = 0.5;  // Minimum value
    $args['step']     = 0.5;  // Quantity steps
    return $args;
}
 
// Variations
add_filter( 'woocommerce_available_variation', 'hoangweb_woocommerce_available_variation' );
function hoangweb_woocommerce_available_variation( $args ) {
    $args['max_qty'] = 80;     // Maximum value (variations)
    $args['min_qty'] = 0.5; // Minimum value (variations)
    return $args;
}
 
// Removes the WooCommerce filter, that is validating the quantity to be an int
remove_filter('woocommerce_stock_amount', 'intval');
 
// Add a filter, that validates the quantity to be a float
add_filter('woocommerce_stock_amount', 'floatval');
 
// Add unit price fix when showing the unit price on processed orders
add_filter('woocommerce_order_amount_item_total', 'hoangweb_unit_price_fix', 10, 5);
function hoangweb_unit_price_fix($price, $order, $item, $inc_tax = false, $round = true) {
    $qty = (!empty($item['qty']) && $item['qty'] != 0) ? $item['qty'] : 1;
    if($inc_tax) {
        $price = ($item['line_total'] + $item['line_tax']) / $qty;
    } else {
        $price = $item['line_total'] / $qty;
    }
    $price = $round ? round( $price, 2 ) : $price;
    return $price;
}

Giải thích:

Giá trị mặc định là 1
Giá trị max là 80
Giá trị min là 0.5
Bước nhảy cho mỗi lần ấn + – là 0.5
Các bạn hoàn toàn có thể thay đổi các giá trị trên. Ví dụ không muốn giới hạn số lượng thì có thể bỏ đi đoạn $args[‘max_value’].

Nếu bạn thích bài viết này, hãy ủng hộ chúng tôi bằng cách đăng ký nhận bài viết mới ở bên dưới và đừng quên chia sẻ kiến thức này với bạn bè của bạn nhé. Bạn cũng có thể theo dõi blog này trên TwitterFacebook

Liên hệ

Công ty chuyên Thiết kế website uy tín nhất Miền Bắc: http://vinastar.net

Hotline tư vấn: 0989 48 3456

Nguồn: Sưu tầm trên internet

You may also like

Leave a Comment