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

Admin
19/06/23
0

    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 = ‘[email protected]’;
                    $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.

    Tổng hợp 24 đoạn code hay cho WooCommerce trong WordPress
    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.

    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.

    Bình luận bài viết (0 bình luận)

    This site uses cookies to offer you a better browsing experience. By browsing this website, you agree to our use of cookies.