WordPress: Overide function với filter hook và action hook
Trong bài viết này mình sẽ hướng dẫn các bạn overide function trong wordpress, bằng cách sử dụng các hook, như filter hook, action hook mời đón đọc.
1. Filter hook là gì
Filter hook là các hook này liên quan đến xử lý lấy nội dung.
1.1 Cú pháp:
1 |
add_filter( string $tag, callable $function_to_add, int $priority = 10, int $accepted_args = 1 ) |
Trong đó:
$tag (tham số bắt buộc): tên của hook filter mà bạn muốn gọi ra, thường là hook filter của wordpress hoặc plugins
$function_to_add (tham số bắt buộc): function này sẽ được gọi khi mà filter hook $tag chạy
$priority (không bắt buộc): Độ ưu tiên của function, giá trị càng thấp thì ưu tiên càng cao. Giá trị mặc định là 10
$accepted_args (không bắt buộc): Giá trị mặc định là 1
1.2 Ví dụ thay đổi hiển thị của form search
1 2 3 4 5 6 7 8 9 10 11 |
/* Overide get_search_form() */ //apply_filters( 'get_search_form', string $form ); function get_search_form_overridden( $form ) { $form = '<form role="search" method="get" class="search-form" action="' . esc_url( home_url( '/' ) ) . '"> <input type="search" class="search-field" placeholder="' . esc_attr_x( 'Tìm kiếm...', 'placeholder' ) . '" value="' . get_search_query() . '" name="s" /> </form>'; return $form; } add_filter( 'get_search_form', 'get_search_form_overridden' ); |
2. Action hook là gì
Action hook là danh sách các hook liên quan đến xử lý sự kiện (hành động).
2. 1 Cú pháp:
1 |
add_action( string $tag, callable $function_to_add, int $priority = 10, int $accepted_args = 1 ) |
Trong đó:
$tag (tham số bắt buộc): tên của action hook mà bạn muốn gọi ra, thường là hook filter của wordpress hoặc plugins
$function_to_add (tham số bắt buộc): function này sẽ được gọi khi mà action hook $tag chạy
$priority (không bắt buộc): Độ ưu tiên của function, giá trị càng thấp thì ưu tiên càng cao. Giá trị mặc định là 10
$accepted_args (không bắt buộc): Giá trị mặc định là 1
2.2 Ví dụ config post type trong wordpress khi setup một theme mới
1 2 3 4 5 6 7 8 9 10 11 12 13 |
add_action( 'after_setup_theme', 'mitatheme_header_setup' ); function mitatheme_header_setup() { add_theme_support( 'custom-header', apply_filters( 'mita_header_args', array( 'default-text-color' => 'fff', 'width' => 1260, 'height' => 240, 'flex-height' => true, ) ) ); add_theme_support( 'post-formats', array( 'gallery', 'quote', 'video', 'aside', 'image', 'link' ) ); add_theme_support( 'title-tag' ); add_theme_support( 'post-thumbnails' ); set_post_thumbnail_size( 825, 510, true ); } |
Trên đây là hai cách hay dùng để overide function trong wordpress.
Hi vọng sẽ giúp được bạn. Thanks