• 14/10/2021 • 8 phút đọc • 11 lượt xem

Tổng hợp các đoạn code hay dùng cho theme bán hàng Flatsome

Việt Lâm Coder
Việt Lâm Coder
Senior Fullstack & System Architect • Hotline: 0944.71.4545

Các đoạn code hay dùng cho theme bán hàng Flatsome: Nói về các Theme bán hàng bằng WordPress thì phải nói ngay đến Flatsome vì nó là lựa chọn hàng đầu cho các Dev khi phát triển Web vì khả năng tùy biến cực cao và dễ dàng. Trong bài viết này Blog thủ thuật máy tính WCT sẽ tổng hợp các đoạn code hay dùng cho theme bán hàng này.

Tổng hợp các đoạn code hay dùng cho theme bán hàng Flatsome

Các đoạn code hay dùng cho theme bán hàng Flatsome


Mình không phải chuyên Code nên có một số cái mình tổng hợp từ các nguồn trên Internet và một số là do mình tự làm , nếu các bạn thấy phù hợp với nhu cầu của mình thì các bạn có thể tham khảo các đoạn code hay dùng cho theme bán hàng Flatsome nhé.

1. Code liên hệ trước hoặc sau chỗ thêm giỏ hàng


<span class="title-hotline"><a href="tel:0972939830">GỌI TƯ VẤN</a></span>
<span class="chat-zalo"><a href="/huong-dan-mua-hang/">HƯỚNG DẪN MUA HÀNG</a></span>
<style>
*, *:before, *:after {
box-sizing: border-box;
}
.chat-zalo {
width: 49%;
background-color: #fd6e1d;
padding: 8px 15px;
display: inline-block;
text-align: center;
border-radius: 5px;
line-height: 20px;
}
.chat-zalo a {
color: #fff;
}
.title-hotline {
width: 49%;
background-color: #fd6e1d;
padding: 8px 10px;
display: inline-block;
text-align: center;
border-radius: 5px;
line-height: 20px;
margin-bottom: 10px;
}
.title-hotline a {
color: #fff;
}
</style>

2. Xóa chữ “Product” trên 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 );


3. Tự thêm sản phẩm vào giỏ mỗi khi khách truy cập vào


/*
* Add item to cart on visit
*/
function add_product_to_cart() {
if ( ! is_admin() ) {
global $woocommerce;
$product_id = 64;
$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' );

4. Thêm ký hiệu tiền tệ theo ý mình


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


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


/**
* 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' );


6. Tự chuyển tới trang thanh toán sau khi thêm vào giỏ


Hiện tại tính năng này không cần sử dụng code nữa mà bạn có thể bật trong Woocommerce -> Settings -> Products -> Display và chọn Redirect to the cart page after successful addition.

7. Gửi email sau khi thanh toán bằng coupon


/**
* 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' );


8. 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' );


9. Tắt 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);


10. Thay chữ “Free” thành một chữ bất kỳ


/**
* WooCommerce Extra Feature
* --------------------------
*
* Replace "Free!" by a custom string
*
*/
function woo_my_custom_free_message() {
return "Liên hệ để lấy giá";
}

add_filter('woocommerce_free_price_html', 'woo_my_custom_free_message');


11. Sửa thông báo sau khi thêm vào giỏ


/**
* Custom Add To Cart Messages
* Add this to your theme functions.php file
**/
add_filter( 'woocommerce_add_to_cart_message', 'custom_add_to_cart_message' );
function custom_add_to_cart_message() {
global $woocommerce;

// Output success messages
if (get_option('woocommerce_cart_redirect_after_add')=='yes') :

$return_to = get_permalink(woocommerce_get_page_id('shop'));

$message = sprintf('<a href="%s" class="button">%s</a> %s', $return_to, __('Continue Shopping &rarr;', 'woocommerce'), __('Product successfully added to your cart.', 'woocommerce') );

else :

$message = sprintf('<a href="%s" class="button">%s</a> %s', get_permalink(woocommerce_get_page_id('cart')), __('View Cart &rarr;', 'woocommerce'), __('Product successfully added to your cart.', 'woocommerce') );

endif;

return $message;
}


12. Tự 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;
}


13. Thay số lượng ảnh thumbnail trong 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
}

14. Hiển thị ảnh đại diện cho category sản phẩm ở trang category


add_action( 'woocommerce_archive_description', 'woocommerce_category_image', 2 );
function woocommerce_category_image() {
if ( is_product_category() ){
global $wp_query;
$cat = $wp_query->get_queried_object();
$thumbnail_id = get_woocommerce_term_meta( $cat->term_id, 'thumbnail_id', true );
$image = wp_get_attachment_url( $thumbnail_id );
if ( $image ) {
echo '<img src="' . $image . '" alt="" />';
}
}
}

15. Sửa đường link 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') );
}


16. Sửa 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 );

17. Ẩn 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);

18. Ảnh sản phẩm bo tròn


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

19. Đưa mô tả sản phẩm vào bên dưới ảnh sản phẩm


add_action('woocommerce_after_shop_loop_item_title','woocommerce_template_single_excerpt', 5);

20. Tắt chức năng mã SKU


add_filter( 'wc_product_sku_enabled', '__return_false' );

21. Code tự động lưu ảnh từ web khác về sever mình


class Auto_Save_Images{

function __construct(){

add_filter( ‘content_save_pre’,array($this,’post_save_images’) );

}

function post_save_images( $content ){

if( ($_POST[‘save’] || $_POST[‘publish’] )){

set_time_limit(240);

global $post;

$post_id=$post->ID;

$preg=preg_match_all(‘/<img.*?src=”(.*?)”/’,stripslashes($content),$matches);

if($preg){

foreach($matches[1] as $image_url){

if(empty($image_url)) continue;

$pos=strpos($image_url,$_SERVER[‘HTTP_HOST’]);

if($pos===false){

$res=$this->save_images($image_url,$post_id);

$replace=$res[‘url’];

$content=str_replace($image_url,$replace,$content);

}

}

}

}

remove_filter( ‘content_save_pre’, array( $this, ‘post_save_images’ ) );

return $content;

}

function save_images($image_url,$post_id){

$file=file_get_contents($image_url);

$post = get_post($post_id);

$posttitle = $post->post_title;

$postname = sanitize_title($posttitle);

$im_name = “$postname-$post_id.jpg”;

$res=wp_upload_bits($im_name,”,$file);

$this->insert_attachment($res[‘file’],$post_id);

return $res;

}

function insert_attachment($file,$id){

$dirs=wp_upload_dir();

$filetype=wp_check_filetype($file);

$attachment=array(

‘guid’=>$dirs[‘baseurl’].’/’._wp_relative_upload_path($file),

‘post_mime_type’=>$filetype[‘type’],

‘post_title’=>preg_replace(‘/\.[^.]+$/’,”,basename($file)),

‘post_content’=>”,

‘post_status’=>’inherit’

);

$attach_id=wp_insert_attachment($attachment,$file,$id);

$attach_data=wp_generate_attachment_metadata($attach_id,$file);

wp_update_attachment_metadata($attach_id,$attach_data);

return $attach_id;

}

}

new Auto_Save_Images();


22. Nếu sản phẩm không có giá sẽ hiển thị 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>’;

}


23. Thêm 1 Tab mới trong Woocormerce


add_filter( ‘woocommerce_product_tabs’, ‘woo_new_product_tab’ );

function woo_new_product_tab( $tabs ) {

// Adds the new tab

$tabs[‘test_tab’] = array(

‘title’ => __( ‘Lịch trình chi tiết’, ‘woocommerce’ ),

‘priority’ => 50,

‘callback’ => ‘woo_new_product_tab_content’

);

return $tabs;

}

function woo_new_product_tab_content() {

// The new tab content

echo “Nội dung”;

}


24. Thêm text tùy chọn vào sau giá


add_filter( 'woocommerce_get_price_html', 'devvn_price_prefix_suffix', 99, 2 );
function devvn_price_prefix_suffix( $price, $product ){
if(is_singular('product')) {
$price = $price . '(Chưa bao gồm VAT)';
}
return apply_filters( 'woocommerce_get_price', $price );
}

25. Code tạo nút liên hệ đẹp cột trái


<div class=”icon-bar”>
<a target=”_blank” rel=”noopener noreferrer” href=”https://www.facebook.com/congtygophuongnam/” class=”float-shadow”>
<img src=”/wp-content/uploads/2019/05/facebook-1.png” alt=”Facebook” title=”Facebook” width=”48″ height=”48″>
</a>

<a target=”_blank” rel=”noopener noreferrer” href=”https://zalo.me/1656335684749387114″ class=”float-shadow”>
<img src=”/wp-content/uploads/2019/05/zalo-1.png” width=”48″ height=”48″ alt=”Zalo” title=”Zalo”>
</a>

<a target=”_blank” rel=”noopener noreferrer” href=”https://www.youtube.com/channel/UCJ3wQAJiZBzum9RWN1TLUYA?view_as=subscriber” class=”float-shadow”>
<img src=”/wp-content/uploads/2019/05/youtube-1.png” width=”48″ height=”48″ alt=”youtube” title=”youtube”>
</a>

</div>


.icon-bar { position: fixed; top: 50%; -webkit-transform: translateY(-50%); -ms-transform: translateY(-50%); transform: translateY(-50%); z-index: 999; }
.icon-bar a { display: block; text-align: center; padding: 6px; transition: all 0.3s ease; color: white; font-size: 20px; }
.icon-bar a:hover { -ms-transform: scale(1.1); /* IE 9 */ -webkit-transform: scale(1.1); /* Safari 3-8 */ transform: scale(1.1); }

Các đoạn code hay dùng cho theme bán hàng Flatsome này được tổng hợp từ: Thạch Pham

Kết luận


Trên đây là một số các đoạn code hay dùng cho theme bán hàng Flatsome mà mình đã tìm tổng hợp từ các Dev, mình cũng đã áp dụng cho các Web bán hàng của mình. Hy vọng nó sẽ có ích với các bạn, chúc bạn thành công.

Việt Lâm Coder

Việt Lâm Coder

Tác giả bài viết và chuyên gia quản trị website. Nếu bạn gặp khó khăn trong quá trình thực hiện hoặc có nhu cầu thiết kế website, lập trình web app Laravel, hãy liên hệ ngay với tôi qua Hotline / Zalo: 0944.71.4545.

☕ Mời Tác Giả Ly Cà Phê Ấm Lòng

Nếu bài viết này giúp ích cho công việc của bạn, hãy tiếp thêm động lực cho tác giả duy trì kho tri thức bằng một ly cà phê ấm lòng nhé!

Mã QR ủng hộ tác giả
Ngân hàng TMCP Quân Đội (MB Bank)TONG VIET LAM

Có Thể Bạn Quan Tâm

Cách Mở Tab Ẩn Danh Trên Safari MacBook Đơn Giản

Cách mở tab ẩn danh trên Safari MacBook sẽ giúp cho người dùng có thể bảo vệ quyền riêng tư và duyệt web một cách an toà...

Hướng dẫn 5 cách tắt update Windows 11 vĩnh viễn chi tiết nhất

Mặc định Windows 11 sẽ được tự động cập nhật trong nền. Tuy nhiên nếu vì lý do nào đó mà bạn không muốn nhận các bản...

Hướng dẫn trỏ file hosts cho domain trên hệ điều hành Windows

– Làm cách nào để 1 website có thể hoạt động trên Share hosting, VPS, Server mà không cần cấu hình các record DNS cho do...

Kích hoạt Cloudflare Turnstile trong Contact Form 7 chống spam

Cloudflare Turnstile là giải pháp xác thực không dùng CAPTCHA giúp bảo vệ website WordPress khỏi spam một cách nhẹ nhàng...

Cách Sử Dụng DeepSeek R1 Miễn Phí Trong Visual Studio Code Với Cline?

Hãy đối mặt với thực tế: Các trợ lý lập trình AI như GitHub Copilot thì tuyệt vời, nhưng chi phí đăng ký của chúng có th...

Gmail API – Tất cả những gì bạn cần biết - 2025

Nếu bạn đang tìm cách tích hợp Gmail vào các ứng dụng của riêng mình thì Gmail API chính là thứ bạn cần! Gmail là một lự...

Hướng dẫn tạo màn hình desktop ảo bằng Task View trên Surface Windows 11

Việt Lâm Coder sẽ hướng dẫn tạo lập nhiều màn hình desktop ảo bằng Task View trên Surface Windows 11 để sắp xếp các tác...

How to Transfer PuTTY Sessions To Another Windows Machine

his is an user contributed article. PuTTY is a terminal emulator application which can act as a client for the SSH, T...

Hướng dẫn cách kiểm tra cổng đang mở (Check open port) trên linux

Với nhiều năm kinh nghiệm hỗ trợ Khách hàng của Tenten, chúng tôi nhận thấy việc thường xuyên theo dõi kiểm tra hoạt độn...

Kiểm tra tất cả các port mà Cyber Panel đang cần có được mở hay không ?

Để kiểm tra tất cả các port cùng một lúc, bạn có thể sử dụng lệnh: netstat -tulpn | grep -E ':(8090|80|443|21|40110|401...

Hướng dẫn cài đặt KeyHelp Panel

Tóm tắt về KeyHelp Bạn đã có phần cứng tốt nhất cho các dự án Internet của mình nhưng việc quản lý phức tạp, hiệu suất...

Tổng hợp danh sách Control Panel VPS free tốt nhất hiện nay

Control Panel VPS free cung cấp một lựa chọn tuyệt vời cho những người dùng muốn quản lý VPS một cách dễ dàng và hiệ...