Skip to content
Thuan Bui's Blog
Go back

Hiển thị Custom Post Type trong trang kết quả tìm kiếm của WordPress

Updated:

Mặc định, WordPress sẽ không hiển thị custom post types trong trang kết quả tìm kiếm. Việc này sẽ ảnh hưởng đến các trang sử dụng custom post types để hiển thị nội dung, ví dụ: các trang sự kiện sử dụng custom post type: event,…

Để hiển thị kết quả từ custom post types vào trang tìm kiếm của WordPress, chúng ta cần phải sử dụng pre_get_posts hook để chỉnh sửa lại main query.

Bạn cần thêm đoạn mã dưới đây vào file functions.php nằm trong thư mục themes đang dùng, hoặc sử dụng plugin Code Snippets (khuyến khích dùng plugin này).

Terminal window
/**
* This function modifies the main WordPress query to include an array of
* post types instead of the default 'post' post type.
*
* @param object $query The main WordPress query.
*/
function tb_include_custom_post_types_in_search_results( $query ) {
if ( $query->is_main_query() && $query->is_search() && ! is_admin() ) {
$query->set( 'post_type', array( 'post', 'event', 'products', 'glossary' ) );
}
}
add_action( 'pre_get_posts', 'tb_include_custom_post_types_in_search_results' );

Hàm tb_include_custom_post_types_in_search_results sẽ chỉnh sửa lại kết quả tìm kiếm bằng cách thêm vào nội dung từ các custom post types: post, event, productsglossary.

Tuỳ theo cấu trúc website đang sử dụng, bạn cần chỉnh sửa lại các custom post types trong hàm trên cho phù hợp.


Share this post on:

Previous Post
[Proxmox] Hướng dẫn cài đặt máy ảo KVM chạy Windows 10 trên Promxox VE
Next Post
Kích hoạt và sử dụng Remote Desktop (RDP) trên Windows 10 / 11