Created
October 30, 2017 08:12
-
-
Save itsKnight847/a0807f2a05311298ad870101cb8149fd to your computer and use it in GitHub Desktop.
limit wordpress search to search by post title only
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Search by Post Title | |
function search_by_title_only( $search, &$wp_query ) | |
{ | |
global $wpdb; | |
if ( empty( $search ) ) | |
return $search; // skip processing - no search term in query | |
$q = $wp_query->query_vars; | |
$n = ! empty( $q['exact'] ) ? '' : '%'; | |
$search = ''; | |
$searchand = ''; | |
foreach ( (array) $q['search_terms'] as $term ) { | |
$term = esc_sql( like_escape( $term ) ); | |
$search .= "{$searchand}($wpdb->posts.post_title LIKE '{$n}{$term}{$n}')"; | |
$searchand = ' AND '; | |
} | |
if ( ! empty( $search ) ) { | |
$search = " AND ({$search}) "; | |
if ( ! is_user_logged_in() ) | |
$search .= " AND ($wpdb->posts.post_password = '') "; | |
} | |
return $search; | |
} | |
add_filter( 'posts_search', 'search_by_title_only', 500, 2 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment