Hook actions and filters in wordpress are the key to helping you intervene deeply into the system without touching the core source code. Mastering this technique gives you complete control over themes and plugins, from inserting tracking code to safely changing data structures.

What are hooks in WordPress and why are they important?
Hooks are checkpoints in the WordPress execution lifecycle that allow programmers to safely insert or change source code. This is extremely important for website development without damaging the system structure when updating to new versions.
At Pham Hai: Personal Blog, we always advise developers to absolutely not edit directly into the core source code (WordPress Core). Instead, Hook provides an intelligent "hook" mechanism. When WordPress runs from top to bottom to load a web page, it stops at pre-declared Hook points to check if there is any custom code that needs to be executed.
Introducing the WordPress Hooks API
WordPress Hook API is the core system that manages all Actions and Filters, helping website components communicate with each other smoothly.
This WordPress API is constantly being upgraded. As of the latest updates in 2026 (like WordPress 6.8 with Block Hooks API), the Hook system has extremely powerful dynamic block insertion support. The knowledge required to write a WordPress Plugin with Hooks must come from understanding this API. To start getting acquainted with this system, mastering the platform when learning basic wordpress is an indispensable stepping stone.
Benefits of using Hook: Flexible customization and easy maintenance
The benefit of Hooks in WordPress lies in the ability to separate custom code from the system core, making it easier for the website to upgrade, maintain, and expand features.
Khi bạn Tùy biến Theme WordPress bằng cách viết code vào file functions.php của Child Theme, các thay đổi sẽ được giữ nguyên vẹn dù theme gốc có cập nhật. Hơn nữa, việc Phát triển Plugin WordPress hoàn toàn dựa vào Hook để tương tác với cơ sở dữ liệu, giúp mã nguồn của bạn trở nên mô-đun hóa, gọn gàng và chuẩn mực theo đúng nguyên tắc lập trình PHP hiện đại.
Distinguishing between Action Hook and Filter Hook - Core difference

Distinguishing Action Hook and Filter Hook in WordPress is very simple: Action is used to add new actions (execute), while Filter is used to edit existing data (transform).
To understand how Action Hooks and Filter Hooks work, you need to visualize how WordPress processes data. One party acts as an "executor" at a specific time, the other party acts as a "filter" that censors and changes information before it is published.
Action Hook: Used to "Execute" an action
Action Hooks allow you to insert PHP code or execute a specific function at a certain time during page load.
Bạn không dùng Action để thay đổi dữ liệu hiện có mà dùng nó để "làm thêm" một việc gì đó. Ví dụ, bạn có thể dùng hook init để khởi tạo một Custom Post Type, dùng save_post để gửi email thông báo tự động ngay khi một bài viết được lưu, hoặc dùng wp_footer để chèn script chat trực tuyến ở cuối trang. Các hàm này không cần trả về (return) bất kỳ giá trị nào.
Filter Hook: Used to "Transform" data
Filter Hook receives input data, processes it through a Callback Function and is required to return modified data before displaying it to the browser.
Nếu Action là "làm đi", thì Filter là "đưa đây tôi sửa rồi mới được dùng". Ví dụ điển hình là hook the_content. Trước khi nội dung bài viết hiển thị cho người đọc, WordPress sẽ đưa nội dung đó qua Filter. Bạn có thể dùng Filter này để tự động thêm nút chia sẻ mạng xã hội vào cuối mỗi bài viết hoặc thay thế các từ ngữ nhạy cảm.
Quick comparison table: Action Hook vs Filter Hook
Below is a summary table to help you easily compare and remember the differences between these two types of hooks.
| Criteria | Action Hook | Filter Hook |
|---|---|---|
| Chức năng chính | Execute a new action/function. | Transform and edit existing data. |
| Hàm sử dụng | add_action() |
add_filter() |
| Yêu cầu trả về (Return) | No return value required. | Bắt buộc phải return giá trị. |
Detailed instructions on how to use Action Hook
How to use WordPress Action Hooks includes defining the hook that needs intervention and attaching a handler function (callback) to it through standard syntax.
Quá trình này diễn ra tại file functions.php hoặc trong các file plugin của bạn. Khi WordPress chạy đến điểm neo đã định, nó sẽ gọi hàm của bạn ra để thực thi.
Cú pháp hàm add_action() và các tham số quan trọng (Priority, Accepted args)
Cú pháp hàm add_action() yêu cầu tên hook, hàm callback, cùng với hai tham số tùy chọn là Độ ưu tiên (Priority) và Tham số (Accepted args).
Cú pháp chuẩn trong PHP: add_action( 'tên_hook', 'tên_hàm_callback', priority, accepted_args );
- Callback Function: Là hàm chứa đoạn mã bạn muốn thực thi.
- Độ ưu tiên (Priority): Mặc định là 10. Số càng nhỏ, hàm càng được chạy sớm. Nếu hai hàm cùng gắn vào một hook, hàm có priority 5 sẽ chạy trước hàm có priority 10.
- Tham số (Accepted args): Số lượng biến mà hàm callback có thể nhận. Mặc định là 1.
Ví dụ về Action Hook trong WordPress: Thêm mã Google Analytics vào wp_head
Ví dụ về Action Hook trong WordPress phổ biến nhất là chèn mã theo dõi Google Analytics trực tiếp vào thẻ <head> của trang web thông qua hook wp_head.
Thay vì mở file header.php ra sửa, bạn chỉ cần thêm đoạn mã sau vào functions.php:
add_action( 'wp_head', 'phamhai_add_google_analytics' );
function phamhai_add_google_analytics() {
?>
<!-- Mã Google Analytics của bạn ở đây -->
<script>
// JS Code
</script>
<?php
}
This method prevents your tracking code from being lost when you update the theme.
WooCommerce Action Hook example: Add a notification after adding a product to the cart
Action Hooks and Filter Hooks in WooCommerce help customize your store extremely powerfully, for example displaying a custom message right after a customer presses the "Add to Cart" button.
WooCommerce cung cấp hàng trăm hook riêng biệt. Để thêm một dòng chữ khuyến mãi dưới nút add to cart, bạn có thể dùng action woocommerce_after_add_to_cart_button.
add_action( 'woocommerce_after_add_to_cart_button', 'phamhai_custom_message_cart' );
function phamhai_custom_message_cart() {
echo '<p class="promo-text">Miễn phí vận chuyển cho đơn hàng hôm nay!</p>';
}
Cách gỡ bỏ một Action với remove_action()
Để vô hiệu hóa một hành động đã được thêm bởi theme hoặc plugin khác, bạn sử dụng hàm remove_action() với đúng tên hook, tên hàm và độ ưu tiên.
Đôi khi, các plugin tự động chèn những đoạn script làm chậm website. Bạn có thể gỡ bỏ chúng bằng cú pháp: remove_action( 'tên_hook', 'tên_hàm_cần_gỡ', priority );. Lưu ý quan trọng là bạn phải gọi remove_action() sau khi hàm gốc đã được khai báo (thường là móc nó vào một hook chạy muộn hơn như wp_loaded).
Detailed instructions on how to use Filter Hook
Cách sử dụng Filter Hook WordPress đòi hỏi bạn phải luôn trả về (return) một giá trị sau khi đã xử lý dữ liệu thông qua hàm add_filter().
Nếu bạn quên lệnh return trong Callback Function của Filter, dữ liệu tại vị trí đó trên website sẽ bị trắng (trống trơn), gây lỗi hiển thị nghiêm trọng.
Cú pháp hàm add_filter() và cách hoạt động
Tương tự như action, hàm add_filter() kết nối một Callback Function với một filter hook cụ thể để thay đổi dữ liệu trước khi nó được xuất ra.
Cú pháp: add_filter( 'tên_filter', 'tên_hàm_callback', priority, accepted_args );
Hàm callback nhận tham số đầu vào là dữ liệu gốc từ WordPress. Bạn dùng PHP để xử lý chuỗi hoặc mảng dữ liệu này, sau đó trả về kết quả cuối cùng.
Ví dụ về Filter Hook trong WordPress: Thay đổi độ dài của đoạn trích (get_the_excerpt)
Ví dụ về Filter Hook trong WordPress thường gặp là giới hạn số lượng từ trong đoạn trích bài viết bằng cách can thiệp vào hook excerpt_length.
By default, WordPress cuts excerpts to 55 words. If your design requires a shorter excerpt (e.g. 20 words), use the following code:
add_filter( 'excerpt_length', 'phamhai_custom_excerpt_length', 999 );
function phamhai_custom_excerpt_length( $length ) {
return 20;
}
Ở đây chúng tôi dùng priority 999 để đảm bảo filter này chạy cuối cùng, ghi đè lên các thiết lập của theme. Ngoài ra, bạn cũng có thể trực tiếp can thiệp nội dung trích dẫn qua hook get_the_excerpt.
Example of Filter Hook in WooCommerce: Edit displayed product price
Bạn có thể dễ dàng thêm tiền tố, hậu tố hoặc thay đổi định dạng giá sản phẩm trên cửa hàng bằng cách sử dụng filter woocommerce_get_price_html.
Let's say you want to add "Just from: " before the price of every product, you apply the code:
add_filter( 'woocommerce_get_price_html', 'phamhai_change_price_display', 10, 2 );
function phamhai_change_price_display( $price, $product ) {
return 'Chỉ từ: ' . $price;
}
Cách gỡ bỏ một Filter với remove_filter()
Hàm remove_filter() cho phép bạn loại bỏ các bộ lọc không mong muốn, giúp khôi phục dữ liệu về trạng thái nguyên bản một cách an toàn.
Just like with actions, you need to pass the exact filter name, the function name attached to it, and the priority level. This is useful when you want to remove WordPress's automatic formatting, such as the automatic quotation mark conversion feature (wpautop).
Advanced: Guide to creating your own WordPress Custom Hooks
This guide to creating Custom Hooks in WordPress helps you build highly scalable themes and plugins that allow others to customize without needing to modify the original code.
When you develop a professional WordPress application, defining your own hooks is a mandatory standard.
When should you create a Custom Hook?
You should create Custom Hooks when you develop complex WordPress applications, want to provide anchor points for other programmers, or break down your own code structure.
For example, you are writing a contact form plugin. Instead of hard-coding the interface, you create a custom hook right below the Submit button. Later, if you want to add a "Sign in with Google" button, you can simply hook into that hook instead of editing the plugin's core file. Before coding these advanced functions, you should test it by install wordpress on localhost to ensure absolute safety of real data.
Cách tạo Action Hook tùy chỉnh với do_action()
Hàm do_action() được đặt tại vị trí bạn muốn tạo điểm neo, cho phép bất kỳ ai dùng add_action() để chèn thêm mã vào vị trí đó.
Trong file template của bạn, hãy chèn dòng:
do_action( 'phamhai_before_main_content' );
Từ thời điểm này, hook phamhai_before_main_content đã tồn tại. Bất cứ ai cũng có thể dùng add_action('phamhai_before_main_content', 'ham_cua_ho') để chèn nội dung vào đúng vị trí bạn đã đặt do_action.
Cách tạo Filter Hook tùy chỉnh với apply_filters()
Bằng cách bọc một biến trong hàm apply_filters(), bạn cho phép các đoạn mã bên ngoài can thiệp và thay đổi giá trị của biến đó trước khi nó được sử dụng tiếp.
Cú pháp khai báo:
$text = apply_filters( 'phamhai_custom_text_filter', 'Nội dung mặc định' );
echo $text;
Nếu không có ai can thiệp, hệ thống sẽ in ra "Nội dung mặc định". Nếu một developer khác dùng add_filter('phamhai_custom_text_filter', ...) để return một chuỗi khác, chuỗi mới đó sẽ được hiển thị.
Optimize performance and improve SEO with Hooks
Optimizing WordPress performance with Hooks and improving search rankings are actual WordPress Hook Applications that bring immense value to admins.
Using smart hooks helps minimize the number of plugins that need to be installed, thereby optimizing page load speed - an important Google ranking factor.
Notes when using Hooks to avoid slowing down the website
Website optimization requires you to not overuse hooks, avoid infinite loops, and strictly control database queries inside callback functions.
Tại Phạm Hải: Blog cá nhân, chúng tôi khuyên bạn nên tránh việc gọi các truy vấn cơ sở dữ liệu nặng (như WP_Query) bên trong các hook chạy nhiều lần trên một trang (ví dụ the_content hoặc các hook trong vòng lặp bài viết). Điều này sẽ làm tăng thời gian phản hồi máy chủ (TTFB) một cách đáng kể.
Ứng dụng Hook WordPress để cải thiện SEO On-page (ví dụ: tùy chỉnh the_title)
Hook WordPress cải thiện SEO bằng cách cho phép bạn tự động chèn các thẻ meta, tối ưu hóa tiêu đề thông qua filter the_title hoặc tự động thêm thuộc tính alt cho ảnh.
For example, you can automatically add the current year to the post title to increase click-through rate (CTR):
add_filter( 'the_title', 'phamhai_add_year_to_title', 10, 2 );
function phamhai_add_year_to_title( $title, $id ) {
if ( in_the_loop() && is_main_query() ) {
return $title . ' [Cập nhật 2026]';
}
return $title;
}
Combined with the necessary SEO wordpress plugins, writing your own hooks will help your website become much lighter and more SEO-compliant.
Effective Hook debugging tools like Query Monitor
Debugging WordPress is a required skill; Using tools like Query Monitor helps you track exactly which hooks are running and how many resources are being consumed.
While working with action hooks and filters in wordpress, there will be times when your code won't run due to Priority conflicts. The Query Monitor plugin provides a visual dashboard that lists all the hooks fired on the current page, what functions are attached to them, and the execution time. From there, you can easily detect bottlenecks and optimize the source code.
Mastering Action Hooks and Filter Hooks opens up a world of unlimited customization in WordPress, allowing developers to build unique and effective solutions. By understanding the "implementation" nature of Actions and the "transformation" nature of Filters, you can safely tamper with almost every aspect of WordPress, creating websites that are powerful, optimized, and easily upgradeable in the future.
Start applying Hooks to your projects today! If you have any questions or interesting examples about action and filter hooks in wordpress, don't hesitate to share in the comments section below.
Lưu ý: 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.