Code to search by post title in WordPress

ARTRU

By default WordPress search, it will compare the search query with the title. post_title, excerpt post_excerpt and content post_content.

In some cases, you only need search results by article title, so you have to write additional custom code to filter the query.

  • Here is a code snippet that filters the query by title only. You can add it to your file function.php or plugin Code Snippets.
function ARTRU_Search_By_Title($columns, $search, $query) {
	return ['post_title'];
}
add_filter('post_search_columns', 'ARTRU_Search_By_Title', 10, 3);
  • If you need more detailed filters, for example Vietnamese with accents, use the code below.
function ARTRU_Search_By_Title_With_Special_Characters($search, $wp_query) {
    global $wpdb;
    $search_term = $wp_query->query_vars['s'];
    if ($search_term) {
        $search = $wpdb->prepare(
            " AND LOWER({$wpdb->posts}.post_title) LIKE BINARY LOWER(%s) ",
            '%' . $wpdb->esc_like($search_term) . '%'
        );
    }
    return $search;
}
add_filter('posts_search', 'ARTRU_Search_By_Title_With_Special_Characters', 10, 2);
COMMENT

Related Articles