magnifying glass on white table

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).

/**
 * 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' );
Code language: PHP (php)

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.

Theo dõi
Thông báo của
guest
0 Comments
Cũ nhất
Mới nhất Được bỏ phiếu nhiều nhất
Phản hồi nội tuyến
Xem tất cả bình luận