NỘI DUNG

Hosting tốc độ cao Vietnix - tốc độ tải trang trung bình dưới 1 giây
VPS siêu tốc Vietnix - trải nghiệm mượt mà, ổn định
08/06/2023
Lượt xem

Tổng hợp 24 đoạn code hay cho WooCommerce trong WordPress

08/06/2023
13 phút đọc
Lượt xem

Đánh giá

5/5 - (184 bình chọn)

WooCommerce là một plugin mã nguồn mở miễn phí được sử dụng nhiều trong hỗ trợ thiết kế website bán hàng. Nếu bạn nắm vững các chức năng và cách sử dụng WooCommerce thì chúng sẽ hỗ trợ bạn rất nhiều trong việc kinh doanh online. Để dễ dàng xây dựng các tính năng trên Woocommerce, trước tiên bạn cần nắm được 24 đoạn code hay cho WooCommerce hiệu quả dưới đây.

1. Thêm ký hiệu tiền tệ tùy thích

add_filter( ‘woocommerce_currencies’, ‘add_my_currency’ ); function add_my_currency( $currencies ) {     $currencies[‘VNĐ’] = __( ‘Vietnam Dong’, ‘woocommerce’ );     return $currencies; }  add_filter(‘woocommerce_currency_symbol’, ‘add_my_currency_symbol’, 10, 2); function add_my_currency_symbol( $currency_symbol, $currency ) {     switch( $currency ) {         case ‘VNĐ’: $currency_symbol = ‘$’; break;     }     return $currency_symbol; }

2. Thay chữ “Add to Cart” hoặc “Thêm vào giỏ hàng”

/**  * Change the add to cart text on single product pages  */  function woo_custom_cart_button_text() {     return __(‘My Button Text’, ‘woocommerce’); } add_filter(‘single_add_to_cart_text’, ‘woo_custom_cart_button_text’);  /**  * Change the add to cart text on product archives  */  function woo_archive_custom_cart_button_text() {     return __( ‘My Button Text’, ‘woocommerce’ ); } add_filter( ‘add_to_cart_text’, ‘woo_archive_custom_cart_button_text’ );

3. Xóa hẳn nút Add to cart

/* Code xoa nut Add to cart */  function remove_loop_button(){     remove_action( ‘woocommerce_after_shop_loop_item’, ‘woocommerce_template_loop_add_to_cart’, 10 );     remove_action( ‘woocommerce_single_product_summary’, ‘woocommerce_template_single_add_to_cart’, 30 ); } add_action(‘init’,’remove_loop_button’);

4. Thêm sản phẩm vào giỏ tự động mỗi khi khách truy cập

Thay YOUR_PRODUCT_ID trong đoạn code thành ID sản phẩm mà bạn muốn tự động thêm vào giỏ hàng.

/*  * Add item to cart on visit  */  function add_product_to_cart() {      if ( ! is_admin() ) {          global $woocommerce;         $product_id = YOUR_PRODUCT_ID;         $found = false;  //check if product already in cart          if ( sizeof( $woocommerce->cart->get_cart() ) > 0 ) {             foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {                 $_product = $values[‘data’];                 if ( $_product->id == $product_id )                     $found = true;             }  // if product not found, add it              if ( ! $found )                 $woocommerce->cart->add_to_cart( $product_id );         } else {  // if no products in cart, add it                          $woocommerce->cart->add_to_cart( $product_id );         }      }  } add_action( ‘init’, ‘add_product_to_cart’ );

5. Xóa mục “Product” thuộc thanh điều hướng

/*  * Hide “Products” in WooCommerce breadcrumb  */  function woo_custom_filter_breadcrumbs_trail ( $trail ) {     foreach ( $trail as $k => $v ) {         if ( strtolower( strip_tags( $v ) ) == ‘products’ ) {             unset( $trail[$k] );             break;         }     }     return $trail; }  add_filter( ‘woo_breadcrumbs_trail’, ‘woo_custom_filter_breadcrumbs_trail’, 10 );

6. Gửi email sau khi sử dụng coupon thanh toán

/**  * WooCommerce Extra Feature  * ————————–  *  * Send an email each time an order with coupon(s) is completed  * The email contains coupon(s) used during checkout process  *  */  function woo_email_order_coupons( $order_id ) {     $order = new WC_Order( $order_id );         if( $order->get_used_coupons() ) {              $to = ‘youremail@yourcompany.com’;                 $subject = ‘New Order Completed’;                 $headers = ‘From: My Name ‘ . “\r\n”;                 $message = ‘A new order has been completed.\n’;                 $message .= ‘Order ID: ‘.$order_id.’\n’;                 $message .= ‘Coupons used:\n’;                  foreach( $order->get_used_coupons() as $coupon) {                     $message .= $coupon.’\n’;                 }                 @wp_mail( $to, $subject, $message, $headers );         } }  add_action( ‘woocommerce_thankyou’, ‘woo_email_order_coupons’ );

7. Thay đổi số lượng sản phẩm liên quan

/**  * WooCommerce Extra Feature  * ————————–  *  * Change number of related products on product page  * Set your own value for ‘posts_per_page’  *  */  function woo_related_products_limit() {     global $product;         $args = array(             ‘post_type’                     => ‘product’,             ‘no_found_rows’                 => 1,             ‘posts_per_page’                => 6,             ‘ignore_sticky_posts’   => 1,             ‘orderby’               => $orderby,             ‘post__in’              => $related,             ‘post__not_in’          => array($product->id)         );         return $args; }  add_filter( ‘woocommerce_related_products_args’, ‘woo_related_products_limit’ );

8. Không cho hiển thị sản phẩm trong Category nào đó ở trang Shop

Bạn thay chữ shoes trong đoạn code dưới đây thành slug của category sản phẩm bạn muốn bỏ đi. Bạn cũng có thể thêm nhiều bằng cách sử dụng mảng array(‘shoes’,’computer’)

/**  * Remove products from shop page by category  *  */  function woo_custom_pre_get_posts_query( $q ) {     if ( ! $q->is_main_query() ) return;     if ( ! $q->is_post_type_archive() ) return;     if ( ! is_admin() && is_shop() ) {          $q->set( ‘tax_query’, array(array(             ‘taxonomy’ => ‘product_cat’,             ‘field’ => ‘slug’,             ‘terms’ => array( ‘shoes’ ), // Don’t display products in the shoes category on the shop page             ‘operator’ => ‘NOT IN’         )));     }     remove_action( ‘pre_get_posts’, ‘custom_pre_get_posts_query’ ); } add_action( ‘pre_get_posts’, ‘woo_custom_pre_get_posts_query’ );

9. Thay chữ “Free” thành chữ bất kỳ

/**  * WooCommerce Extra Feature  * ————————–  *  * Replace “Free!” by a custom string  *  */  function woo_my_custom_free_message() {     return “Liên hệ báo giá”; } add_filter(‘woocommerce_free_price_html’, ‘woo_my_custom_free_message’);

10. Ẩn các phương thức vận chuyển khác khi kích hoạt phương thức miễn phí

// Hide ALL shipping options when free shipping is available  add_filter( ‘woocommerce_available_shipping_methods’, ‘hide_all_shipping_when_free_is_available’ , 10, 1 );  /**  * Hide ALL Shipping option when free shipping is available  *  * @param array $available_methods  */  function hide_all_shipping_when_free_is_available( $available_methods ) {     if( isset( $available_methods[‘free_shipping’] ) ) :      // Get Free Shipping array into a new array          $freeshipping = array();         $freeshipping = $available_methods[‘free_shipping’];          // Empty the $available_methods array          unset( $available_methods );          // Add Free Shipping back into $avaialble_methods         $available_methods = array();            $available_methods[] = $freeshipping;      endif;      return $available_methods;  }

11. Thay đổi số lượng ảnh thumbnail sản phẩm

add_filter ( ‘woocommerce_product_thumbnails_columns’, ‘xx_thumb_cols’ );  function xx_thumb_cols() {     return 4; // .last class applied to every 4th thumbnail }

12. Sửa đổi đường dẫn điều hướng nút “Add to Cart”

add_filter(‘add_to_cart_redirect’, ‘custom_add_to_cart_redirect’);  function custom_add_to_cart_redirect() {      /**     * Replace with the url of your choosing     * e.g. return ‘http://www.yourshop.com/’     */      return get_permalink( get_option(‘woocommerce_checkout_page_id’) ); }

13. Thay đổi số lượng sản phẩm hiển thị ở mỗi trang

// Display 24 products per page. Goes in functions.php  add_filter( ‘loop_shop_per_page’, create_function( ‘$cols’, ‘return 24;’ ), 20 );

14. Thêm mô tả sản phẩm vào dưới ảnh sản phẩm

add_action(‘woocommerce_after_shop_loop_item_title’,’woocommerce_template_single_excerpt’, 5);

15. Đóng các tab như Review, Description trong sản phẩm

/**  * Remove product tabs  *  */ function woo_remove_product_tab($tabs) {     unset( $tabs[‘description’] );      		// Remove the description tab     unset( $tabs[‘reviews’] ); 					// Remove the reviews tab     unset( $tabs[‘additional_information’] );  	// Remove the additional information tab  	return $tabs; } add_filter( ‘woocommerce_product_tabs’, ‘woo_remove_product_tab’, 98);

16. Tự động thêm tỉnh/thành (States)

/**  * Code goes in functions.php or a custom plugin. Replace XX with the country code your changing.  */ add_filter( ‘woocommerce_states’, ‘custom_woocommerce_states’ ); function custom_woocommerce_states( $states ) {   $states[‘XX’] = array(     ‘XX1’ => ‘State 1’,     ‘XX2’ => ‘State 2’   );   return $states; }

17. Thay đổi chiều dài field nhập địa chỉ

add_filter(‘woocommerce_billing_fields’, ‘custom_woocommerce_billing_fields’); function custom_woocommerce_billing_fields( $fields ) {     $fields[‘billing_address_1’][‘class’] = array( ‘form-row-wide’ );     $fields[‘billing_address_2’][‘class’] = array( ‘form-row-wide’ );     return $fields; }

18. Vòng lặp hiển thị sản phẩm

<ul class="products">     <?php $args = array( ‘post_type’ => ‘product’, ‘posts_per_page’ => 12); 		$loop = new WP_Query( $args ); 		if ( $loop->have_posts() ) { 			while ( $loop->have_posts() ) : $loop->the_post(); 			    woocommerce_get_template_part( ‘content’, ‘product’ ); 			endwhile; 		} else { 			echo __( ‘No products found’ ); 		} 		wp_reset_postdata(); 	?> </ul>  <!–/.products–>

19. Ẩn các sản phẩm liên quan

/*  * wc_remove_related_products  *  * Clear the query arguments for related products so none show.  * Add this code to your theme functions.php file.  */ function wc_remove_related_products( $args ) { 	return array(); } add_filter(‘woocommerce_related_products_args’,’wc_remove_related_products’, 10);

20. Xóa menu kiểu sắp xếp tùy chỉnh sản phẩm

remove_action( ‘woocommerce_before_shop_loop’, ‘woocommerce_catalog_ordering’, 30 );

21. Bo tròn ảnh sản phẩm

Code này thì thêm vào file style.css trong themes:

.woocommerce .woocommerce-tabs {border: 1px solid #e6e6e6}

22. Thay đổi tiêu đề “Giỏ hàng” thành “Giỏ hàng của bạn”

add_filter('gettext', 'thay_đổi_tên_giỏ_hàng', 20, 3); function thay_đổi_tên_giỏ_hàng($translated_text, $text, $domain){     if($text === 'Giỏ hàng' && $domain === 'woocommerce'){         $translated_text = 'Giỏ hàng của bạn';     }     return $translated_text; }

23. Ẩn giá sản phẩm trên trang danh sách sản phẩm

add_filter('woocommerce_get_price_html', 'ẩn_giá_sản_phẩm'); function ẩn_giá_sản_phẩm($price){     if(is_shop()){         $price = '';     }     return $price; }

24. Thêm trường tùy chỉnh vào trang thanh toán

add_action('woocommerce_after_order_notes', 'thêm_trường_tùy_chỉnh_thanh_toán'); function thêm_trường_tùy_chỉnh_thanh_toán($checkout){     echo '<div id="custom-field-wrapper">';     woocommerce_form_field('custom_field', array(         'type' => 'text',         'class' => array('my-field-class form-row-wide'),         'label' => __('Trường tùy chỉnh', 'woocommerce'),         'placeholder' => __('Nhập thông tin', 'woocommerce')     ), $checkout->get_value('custom_field'));     echo '</div>'; } 

Để thêm các đoạn code trên, bạn cần tìm đến file functions.php đang sử dụng bằng cách vào WP Admin > Appearance > Theme File Editor > tìm file functions.php. Đoạn code tùy chỉnh ở trên sẽ được thêm vào sau phần <?php, tốt nhất nên thêm đoạn code mới vào phần dưới cùng file.

Thêm code vào file functions.php
Thêm code vào file functions.php

Để xây dựng website bán hàng chuyên nghiệp trên nền tảng WordPress, việc hiểu rõ về code hỗ trợ cho WooCommerce là điều rất cần thiết. Tuy nhiên, để tối ưu hóa hiệu quả việc kinh doanh trên website, bạn cần phải tìm kiếm và cài đặt thêm các plugin hỗ trợ cho WooCommerce.

Hiện nay, khi mua các gói hosting, VPS tốc độ cao tại Vietnix, bạn sẽ được tặng miễn phí nhiều theme và plugin WordPress trị giá tới 800 USD, trong đó có những plugin hữu ích cho WooCommerce như plugin Woocommerce Checkout Field, WooCommerce Products Already Added To Cart Or Purchased,… Những plugin này sẽ giúp bạn nâng cao tính năng, cải thiện trải nghiệm mua sắm của khách hàng trên website của mình. Liên hệ với Vietnix để được tư vấn chi tiết.

Trên đây là 24 đoạn code hay cho Woocommerce trong WordPress, hy vọng sẽ hữu ích với bạn. Chúc các bạn thực hành thành công. Nếu còn bất cứ vấn đề gì thắc mắc, bạn vui lòng để lại bình luận ngay bên dưới để được hỗ trợ thêm.

THEO DÕI VÀ CẬP NHẬT CHỦ ĐỀ BẠN QUAN TÂM

Đăng ký ngay để nhận những thông tin mới nhất từ blog của chúng tôi. Đừng bỏ lỡ cơ hội truy cập kiến thức và tin tức hàng ngày

Chọn chủ đề :

Lê Nam

WordPress Expert
tại

Kết nối với mình qua

Kết nối với mình qua

Theo dõi
Thông báo của
guest
0 Comments
Phản hồi nội tuyến
Xem tất cả bình luận

Tăng tốc độ website - Nâng tầm giá trị thương hiệu

Tăng tốc tải trang

95 điểm

Nâng cao trải nghiệm người dùng

Tăng 8% tỷ lệ chuyển đổi

Thúc đẩy SEO, Google Ads hiệu quả

Tăng tốc ngay

SẢN PHẨM NỔI BẬT

7 NGÀY DÙNG THỬ HOSTING

NẮM BẮT CƠ HỘI, THÀNH CÔNG DẪN LỐI

Cùng trải nghiệm dịch vụ hosting tốc độ cao được hơn 100,000 khách hàng sử dụng

ĐĂNG KÝ NHẬN TÀI LIỆU THÀNH CÔNG
Cảm ơn bạn đã đăng ký nhận tài liệu mới nhất từ Vietnix!
ĐÓNG

ĐĂNG KÝ DÙNG THỬ HOSTING

7 NGÀY MIỄN PHÍ

ĐĂNG KÝ DÙNG THỬ HOSTING

7 NGÀY MIỄN PHÍ

XÁC NHẬN ĐĂNG KÝ DÙNG THỬ THÀNH CÔNG
Cảm ơn bạn đã đăng ký thông tin thành công. Đội ngũ CSKH sẽ liên hệ trực tiếp để kích hoạt dịch vụ cho bạn nhanh nhất!
ĐÓNG