Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
limit WP search to titles only
<?php
add_filter ( 'posts_search', 'rkv_search_by_title_only', 500, 2 );
/**
* restrict search query to only compare titles
* @param string $search search query passed by user
* @param mixed $wp_query global query from WP being modified
* @return mixed search results
*/
function rkv_search_by_title_only( $search, $wp_query ) {
global $wpdb;
// skip processing - no search term in query
if ( empty( $search ) ) {
return $search;
}
$q = $wp_query->query_vars;
$n = ! empty( $q['exact'] ) ? '' : '%';
$search = '';
$s_and = '';
foreach ( (array) $q['search_terms'] as $term ) :
$term = esc_sql( like_escape( $term ) );
$search .= "{$s_and}($wpdb->posts.post_title LIKE '{$n}{$term}{$n}')";
$s_and = ' AND ';
endforeach;
if ( ! empty( $search ) ) {
$search = " AND ({$search}) ";
if ( ! is_user_logged_in() ) {
$search .= " AND ($wpdb->posts.post_password = '') ";
}
}
return $search;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment