This article summarizes the advanced but extremely easy to apply WooCommerce PHP feature code, helping you customize your sales website professionally without having to install too many additional plugins. At Pham Hai: Personal Blog, we will guide you in detail how to change the purchase button, set up the payment page, optimize speed and add product information fields quickly and safely to enhance user experience and increase conversion rates.

The most common PHP code snippets to customize product pages and store pages
customizing WooCommerce with PHP code on the product page helps you completely control the display interface, from purchase buttons to detailed information without weighing down the website. Below are the most commonly used WooCommerce code snippets.
The code changes the text and color of the "Add to cart" button to attract customers
Bạn có thể sử dụng filter woocommerce_product_single_add_to_cart_text để đổi chữ mặc định thành thông điệp hấp dẫn hơn nhằm tăng tỷ lệ chuyển đổi.
Code thay đổi nút "Thêm vào giỏ hàng" là một thủ thuật nhỏ nhưng mang lại hiệu quả tâm lý lớn. Thay vì dòng chữ mặc định nhàm chán, bạn có thể biến tấu chúng thành "Mua Ngay Giảm 10%" hoặc "Thêm Vào Giỏ - Freeship". Dưới đây là đoạn mã PHP bạn cần sử dụng:
// Đổi chữ nút Thêm vào giỏ hàng ở trang chi tiết sản phẩm
add_filter( 'woocommerce_product_single_add_to_cart_text', 'phamhai_custom_cart_button_text' );
function phamhai_custom_cart_button_text() {
return __( 'Mua Ngay Giảm 10%', 'woocommerce' );
}
// Đổi chữ nút Thêm vào giỏ hàng ở trang cửa hàng (Shop/Archive)
add_filter( 'woocommerce_product_add_to_cart_text', 'phamhai_archive_custom_cart_button_text' );
function phamhai_archive_custom_cart_button_text() {
return __( 'Mua Ngay', 'woocommerce' );
}
The code adds custom fields to the product page
To add WooCommerce product custom fields with code, you need to incorporate action hooks to display the input box in the admin area and save the data to the database.
Sometimes, WooCommerce's default information fields are not enough. If you sell electronics, you may need to add a "Warranty Period" field. The following code helps you create a basic custom field:
// 1. Hiển thị trường tùy chỉnh trong bảng dữ liệu sản phẩm
add_action( 'woocommerce_product_options_general_product_data', 'phamhai_add_custom_field' );
function phamhai_add_custom_field() {
woocommerce_wp_text_input( array(
'id' => '_thoi_gian_bao_hanh',
'label' => __( 'Thời gian bảo hành', 'woocommerce' ),
'placeholder' => 'VD: 12 tháng',
'desc_tip' => 'true',
'description' => __( 'Nhập thời gian bảo hành cho sản phẩm này.', 'woocommerce' )
) );
}
// 2. Lưu dữ liệu trường tùy chỉnh
add_action( 'woocommerce_process_product_meta', 'phamhai_save_custom_field' );
function phamhai_save_custom_field( $post_id ) {
$custom_field_value = isset( $_POST['_thoi_gian_bao_hanh'] ) ? $_POST['_thoi_gian_bao_hanh'] : '';
update_post_meta( $post_id, '_thoi_gian_bao_hanh', sanitize_text_field( $custom_field_value ) );
}
Code to customize how product attributes are displayed (hide/show, change position)
Sử dụng filter woocommerce_display_product_attributes là cách tối ưu nhất để code tùy chỉnh hiển thị thuộc tính sản phẩm WooCommerce theo đúng ý định thiết kế của bạn.
When managing Product Attributes and Product Variations, sometimes you want to hide some internal attributes from being visible to customers in the "Additional Information" tab. You can apply the following code:
add_filter( 'woocommerce_display_product_attributes', 'phamhai_hide_specific_attributes', 10, 2 );
function phamhai_hide_specific_attributes( $product_attributes, $product ) {
// Thay 'pa_mau-sac' bằng slug thuộc tính bạn muốn ẩn
if ( isset( $product_attributes['pa_mau-sac'] ) ) {
unset( $product_attributes['pa_mau-sac'] );
}
return $product_attributes;
}
The code changes the "Related Products" title to more attractive sales content
Đổi tiêu đề "Sản phẩm liên quan" thành "Khách hàng cũng mua" giúp kích thích nhu cầu mua sắm bằng cách sử dụng filter woocommerce_product_related_products_heading.
A strong suggestive title will bring better upselling results. Insert this code to change the default title:
add_filter( 'woocommerce_product_related_products_heading', 'phamhai_rename_related_products' );
function phamhai_rename_related_products() {
return __( 'Khách hàng thường mua kèm với', 'woocommerce' );
}
The code automatically adds a product to the cart when a visitor visits
Tính năng này cực kỳ hữu ích cho các chiến dịch tặng quà miễn phí. Bạn có thể dùng action template_redirect để tự động add sản phẩm vào giỏ hàng.
If you're running a "Free tote bag with every order" program, the code below will help you automate that process without the customer having to do anything:
add_action( 'template_redirect', 'phamhai_auto_add_product_to_cart' );
function phamhai_auto_add_product_to_cart() {
if ( ! is_admin() ) {
$product_id = 123; // Thay 123 bằng ID sản phẩm quà tặng
$found = false;
// Kiểm tra xem sản phẩm đã có trong giỏ chưa
if ( sizeof( WC()->cart->get_cart() ) > 0 ) {
foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
$_product = $values['data'];
if ( $_product->get_id() == $product_id )
$found = true;
}
// Nếu chưa có thì thêm vào
if ( ! $found )
WC()->cart->add_to_cart( $product_id );
}
}
}
Enhance your checkout experience with custom shopping cart and checkout page code
Optimizing your Checkout Process is vital to reducing cart abandonment rates. Applying the WooCommerce Checkout Page Customization Code helps the form become neater, more professional, and more user-friendly.
WooCommerce checkout page customization code: add, remove or rearrange fields
Bằng cách can thiệp vào filter woocommerce_checkout_fields, bạn có thể dễ dàng loại bỏ các trường không cần thiết như mã bưu điện (Postcode) hoặc tên công ty để làm ngắn biểu mẫu.
Many customers feel annoyed when they have to fill in too much information. In Vietnam, the postal code field is usually not required. You can hide it with the following code:
add_filter( 'woocommerce_checkout_fields' , 'phamhai_remove_checkout_fields' );
function phamhai_remove_checkout_fields( $fields ) {
unset($fields['billing']['billing_company']); // Ẩn tên công ty
unset($fields['billing']['billing_postcode']); // Ẩn mã bưu điện
unset($fields['billing']['billing_address_2']); // Ẩn địa chỉ dòng 2
return $fields;
}
The code adds a "Buy Now" button to redirect directly to the payment page
The "Buy Now" button helps shorten the purchasing journey. The code below will create a button that redirects directly to the checkout page instead of just adding to cart.
This feature is especially suitable for landing pages that sell single products.
add_action( 'woocommerce_after_add_to_cart_button', 'phamhai_add_buy_now_button' );
function phamhai_add_buy_now_button() {
global $product;
$checkout_url = wc_get_checkout_url();
echo '<button type="submit" name="add-to-cart" value="' . esc_attr( $product->get_id() ) . '" class="single_add_to_cart_button button alt phamhai-buy-now" id="buy_now_button" data-checkout_url="' . esc_url( $checkout_url ) . '">Mua Ngay</button>';
}
(Lưu ý: Bạn có thể cần thêm một chút JavaScript để xử lý sự kiện click chuyển hướng trực tiếp).
Code changes the word "Free" of a product priced at 0 VND to "Contact price"
For products without prices or fluctuating prices, displaying "Contact Price" will be much more professional than the system's default "Free".
add_filter( 'woocommerce_empty_price_html', 'phamhai_custom_empty_price_message' );
add_filter( 'woocommerce_variable_empty_price_html', 'phamhai_custom_empty_price_message' );
function phamhai_custom_empty_price_message() {
return 'Giá liên hệ';
}
The code adds notes and suffixes after the product price (for example: "VAT included")
Adding a price suffix helps make detailed cost information transparent for customers, avoiding unnecessary misunderstandings during the payment process.
add_filter( 'woocommerce_get_price_html', 'phamhai_add_price_suffix', 100, 2 );
function phamhai_add_price_suffix( $price, $product ) {
$suffix = ' <span class="price-suffix">(Đã bao gồm VAT)</span>';
return $price . $suffix;
}
Instructions on how to add PHP code to WooCommerce safely and properly
To How to add PHP code to WooCommerce not crash the website, you absolutely must not insert it directly into the core files but must use Child Theme or a specialized plugin.
Method 1: Using Child Theme's functions.php file (Recommended)
Inserting code into the functions.php file of Child Theme ensures your customizations are not lost when you update the original interface to the new version.
Tại Phạm Hải: Blog cá nhân, chúng tôi luôn khuyến khích các nhà phát triển sử dụng phương pháp này. Bạn chỉ cần vào WordPress Dashboard, điều hướng đến mục Giao diện > Tùy chỉnh giao diện (Theme File Editor), chọn file functions.php của Child Theme và dán đoạn mã vào cuối file. Cuối cùng, nhấn "Cập nhật tập tin" để lưu lại.
Method 2: Use Code Snippets plugin (Safe for beginners)
If you are not technically savvy, Code Snippets plugin is the perfect solution to manage PHP code snippets right in the admin page without touching system files.
Using this Plugin helps you easily enable/disable each woocommerce php feature code in the same way as managing child plugins. If a piece of code causes an error, the plugin will automatically disable it, keeping your site safe.
Important notes to know before inserting code to avoid causing website errors
Always back up the entire website and check the PHP limit parameter before executing any new code to prevent white screen errors (White Screen of Death).
- Sao lưu cơ sở dữ liệu: Thao tác bắt buộc trước khi chỉnh sửa.
- Sử dụng môi trường Staging: Hãy thử nghiệm code trên trang web nháp trước khi đưa lên trang chính thức.
- Hiểu rõ hệ thống: Nếu bạn chưa nắm rõ kiến thức nền tảng, việc tìm hiểu woocommerce là gì sẽ giúp bạn làm chủ hệ thống này tốt hơn và tránh các sai sót cơ bản.
Expand features and optimize WooCommerce speed with code
Extending WooCommerce features with code not only helps diversify functionality but also supports Performance optimization much more strongly than abusing the installation of third-party extensions.
Introducing WooCommerce Hooks (Actions and Filters) - The key to customizing every feature
Sử dụng WooCommerce hooks và filters là tiêu chuẩn kỹ thuật để can thiệp vào mã nguồn. Trong đó, WooCommerce Actions dùng để chèn nội dung mới, còn WooCommerce Filters dùng để sửa đổi dữ liệu có sẵn.
| Hook type | Main function | Typical example |
|---|---|---|
| Actions | Add content, execute functionality at a specific location. | woocommerce_before_single_product |
| Filters | Filter, change, or reformat data before displaying. | woocommerce_get_price_html |
Understanding WooCommerce Hooks is an important stepping stone. To design a more complex data system on a sales website, you can refer to create custom post type wordpress code combined with WooCommerce.
The code optimizes speed by removing unnecessary WooCommerce CSS and JS
Tối ưu tốc độ WooCommerce bằng code thông qua việc vô hiệu hóa các file script trên các trang không phục vụ mục đích bán hàng (như trang Giới thiệu, Liên hệ) giúp giảm tải đáng kể cho server.
WooCommerce loads CSS and JS across the entire website by default. To prevent this, use the following code:
add_action( 'wp_enqueue_scripts', 'phamhai_dequeue_woocommerce_styles_scripts', 99 );
function phamhai_dequeue_woocommerce_styles_scripts() {
// Nếu không phải trang liên quan đến WooCommerce thì loại bỏ scripts
if ( function_exists( 'is_woocommerce' ) ) {
if ( ! is_woocommerce() && ! is_cart() && ! is_checkout() && ! is_account_page() ) {
wp_dequeue_style( 'woocommerce-layout' );
wp_dequeue_style( 'woocommerce-smallscreen' );
wp_dequeue_style( 'woocommerce-general' );
wp_dequeue_script( 'wc-add-to-cart' );
wp_dequeue_script( 'wc-cart-fragments' );
}
}
}
Collection of commonly used WooCommerce Shortcodes to display products flexibly
Shortcode cho phép bạn gọi và hiển thị danh sách sản phẩm ở bất kỳ đâu trên website như trang chủ, bài viết blog hay landing page một cách cực kỳ linh hoạt.
These shortcodes often work based on the system's implicit queries, similar to applying the wp_query wordpress loop to get accurate post data. Here are some basic shortcodes:
[products limit="4" columns="4" orderby="popularity"]: Hiển thị 4 sản phẩm bán chạy nhất.[featured_products limit="8" columns="4"]: Hiển thị các sản phẩm nổi bật.[sale_products limit="4"]: Hiển thị các sản phẩm đang giảm giá.
Using WooCommerce PHP feature code is an incredibly powerful method to deeply customize and optimize your online store. Instead of depending on dozens of plugins that can slow down website loading speed, you can completely control, customize and enhance core features. At Pham Hai: Personal Blog, we hope that with the safe and accurate code compiled in this article, you will easily apply it successfully to build a professional, smooth sales website that brings outstanding business efficiency.
Do you need additional code for a specific feature? Please leave your request in the comments section below, we will assist you!
Lưu ý: Các thông tin trong bài viết này chỉ mang tính chất tham khảo. Để có lời khuyên tốt nhất, vui lòng liên hệ trực tiếp với chúng tôi để được tư vấn cụ thể dựa trên nhu cầu thực tế của bạn.