Bài viết này mình chia sẻ đến bạn đoạn code có thể cải thiện tính năng tìm kiếm trên theme GeneratePress rất đáng kể. Mình trước đây có dùng plugin để tìm kiếm tiện lợi hơn, tuy nhiên phương án đó hơi nặng. Sau này làm lại blog thì mình không sử dụng plugin đó nữa, mà thêm code bên dưới vào theme để tính năng tìm kiếm ngon lành, chuẩn chỉnh hơn so với mặc định của WordPress.

Mình không hiểu tại sao tính năng tìm kiếm mặc định của WordPress lại tệ như vậy, bao nhiêu năm rồi mà giống kiểu làm cho có. Tìm một từ khoá đơn giản thôi mà xem kết quả hiển thị thấy ức chế thật sự. Kết quả hiển thị rất là ho lao luôn, bài đúng ra phải hiển thị lên đầu kết quả tìm kiếm thì nó xếp ở tận đâu đâu. Nói chung bạn dùng code của mình bên dưới và so sánh với tính năng tìm kiếm mặc định sẽ thấy sự khác biệt rõ rệt ^^
Nói sơ qua về hướng của mình: Kết quả sẽ ưu tiên xếp bài viết có chứa nhiều khoá nhiều nhất thì lên đầu, số lần từ khoá xuất hiện càng ít thì đẩy xuống dưới, đồng thời hiển thị số lần từ khoá xuất hiện ở mỗi kết quả để người dùng nhìn thấy. Để sử dụng code này thì bạn copy và dán vào cuối file functions.php của theme/ child theme đang sử dụng là được.
//CẢI THIỆN TÌM KIẾM MẶC ĐỊNH THEME GENERATEPRESS
function hocban_search_only_post(WP_Query $query):void{
if(is_admin()||!$query->is_main_query()||!$query->is_search()||!is_search())return;
$query->set('post_type','post');
$query->set('post_status','publish');
$s=get_search_query(false);
if(!is_string($s)||trim($s)==='')return;
$s=trim($s);
global $wpdb;
$like='%'.$wpdb->esc_like($s).'%';
$where_callback=static function(string $where)use($like,$wpdb):string{
$extra=$wpdb->prepare(" AND ({$wpdb->posts}.post_title LIKE %s OR {$wpdb->posts}.post_content LIKE %s OR {$wpdb->posts}.post_excerpt LIKE %s)",$like,$like,$like);
return $where.$extra;
};
add_filter('posts_where',$where_callback,10);
add_action('loop_end',static function()use($where_callback){remove_filter('posts_where',$where_callback,10);},1);
}
add_action('pre_get_posts','hocban_search_only_post');
function hocban_order_by_count(string $orderby,WP_Query $query):string{
if(is_admin()||!$query->is_main_query()||!$query->is_search())return $orderby;
$s=trim((string)get_search_query(false));
if($s==='')return $orderby;
global $wpdb;
$lower_s=mb_strtolower($s);
$score=$wpdb->prepare("((LENGTH(LOWER({$wpdb->posts}.post_content))-LENGTH(REPLACE(LOWER({$wpdb->posts}.post_content),%s,'')))+(LENGTH(LOWER({$wpdb->posts}.post_title))-LENGTH(REPLACE(LOWER({$wpdb->posts}.post_title),%s,'')))*10)DESC",$lower_s,$lower_s);
return $score.",{$wpdb->posts}.post_modified DESC";
}
add_filter('posts_orderby','hocban_order_by_count',10,2);
function hocban_show_keyword_count():void{
if(!is_search()||!in_the_loop()||!is_main_query())return;
$s=trim((string)get_search_query(false));
if($s==='')return;
global $post;
if(!$post instanceof WP_Post||!isset($post->post_content,$post->post_title))return;
$haystack=' '.wp_strip_all_tags($post->post_content).' '.wp_strip_all_tags($post->post_title).' ';
$count=mb_substr_count(mb_strtolower($haystack),mb_strtolower($s),'UTF-8');
if($count>0){
$output=sprintf('<p class="hocban-search-count">Từ khóa <span class="hocban-highlight">%s</span> xuất hiện <strong>%s</strong> lần trong bài viết này</p>',esc_html($s),number_format_i18n($count));
echo wp_kses($output,['p'=>['class'=>[]],'span'=>['class'=>[]],'strong'=>[]]);
}
}
add_action('generate_after_entry_title','hocban_show_keyword_count');
function hocban_search_css():void{
if(!is_search())return;
$css='.hocban-search-count{margin:12px 0 18px;font-size:15px;color:#222;font-weight:500;line-height:1.5;}.hocban-highlight{background:#fff000;color:#000;padding:3px 10px;border-radius:6px;font-weight:900;box-shadow:0 2px 6px rgba(0,0,0,0.25);display:inline-block;}.hocban-search-count strong{color:#d00;font-size:18px;font-weight:900;}';
wp_add_inline_style('generate-style',$css);
}
add_action('wp_enqueue_scripts','hocban_search_css',99);
//HẾT CODE CẢI THIỆN TÌM KIẾM MẶC ĐỊNH