Tổng hợp code hay cho WooCommerce trong WordPress 2024

tong hop code hay wordpress
tong hop code hay wordpress

Tổng hợp code hay cho wordpress được thu thập từ nhiều nguồn

Để sử dụng an toàn, các bạn cần backup website trước khi thực hiện

Để 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.

1 số đoạn code wordpress sẽ được chèn ở file style.css cần lưu ý

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

/**
* 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ỳ


/**
* 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. Sắp xếp sản phẩm hết hàng xuống dưới

add_filter('posts_clauses', 'order_by_stock_status');
function order_by_stock_status($posts_clauses) {
global $wpdb;
// only change query on WooCommerce loops
if (is_woocommerce() && (is_shop() || is_product_category() || is_product_tag())) {
$posts_clauses['join'] .= " INNER JOIN $wpdb->postmeta istockstatus ON ($wpdb->posts.ID = istockstatus.post_id) ";
$posts_clauses['orderby'] = " istockstatus.meta_value ASC, " . $posts_clauses['orderby'];
$posts_clauses['where'] = " AND istockstatus.meta_key = '_stock_status' AND istockstatus.meta_value <> '' " . $posts_clauses['where'];
}
return $posts_clauses;
}

17. Code chuyển sản phẩm không có giá thành “Liên hệ”

add_filter('woocommerce_empty_price_html', 'custom_call_for_price'); 
function custom_call_for_price() 
{ return '<span class="lien-he-price">Liên hệ</span>'; }

18. Cách ẩn thông báo đăng ký flatsome

 add_action( 'init', 'hide_notice' );
function hide_notice() {
   remove_action( 'admin_notices', 'flatsome_maintenance_admin_notice' );
}


19. 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}


20. 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;
}


21. Ẩ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;
}


22. 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>’;
}


Trên đây là tổng hợp code hay cho Woo trong WordPress Vietgear hay dùng, chúc các bạn thành công.




Trả lời

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 *