Last active
June 25, 2025 07:15
-
-
Save rmpel/b27229ee792b470f3219621637935bf0 to your computer and use it in GitHub Desktop.
WordPress Admin Post search by 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
<?php | |
// mu-plugin or included in theme/plugin | |
add_filter( 'posts_search', 'maybe_search_by_title_only', 10, 2 ); | |
// add query var 'title_only' to the allowed query vars. | |
add_filter( 'query_vars', function ( $vars ) { | |
$vars[] = 'title_only'; | |
return $vars; | |
} ); | |
// add a checkbox to the admin post search form to search by title only. | |
add_action( 'restrict_manage_posts', function () { | |
if ( ! is_admin() || ! current_user_can( 'edit_posts' ) ) { | |
return; | |
} | |
// Add a checkbox to the search form. | |
echo '<label for="title_only" style="margin: 0 10px; line-height: 2.5em;">'; | |
echo '<input type="checkbox" id="title_only" name="title_only" value="1" ' . checked( isset( $_GET['title_only'] ), true, false ) . ' />'; | |
echo __( 'Search by title only' ); | |
echo '</label>'; | |
} ); | |
/** | |
* Modify the search query to search by title only, if the 'title_only' query var is set, and only in the admin area. | |
* | |
* @param string $search The search SQL. | |
* @param WP_Query $wp_query The WP_Query instance. | |
* @return string Modified search SQL. | |
*/ | |
function maybe_search_by_title_only( $search, $wp_query ) { | |
if ( ! is_admin() || empty( $search ) ) { | |
return $search; | |
} | |
global $wpdb; | |
$q = $wp_query->query_vars; | |
// Detect if the search is for titles only. | |
if ( empty( $q['title_only'] ) || ! (int) $q['title_only'] ) { | |
return $search; | |
} | |
$x = ! empty( $q['exact'] ) ? '' : '%'; | |
$search = ''; | |
$searchand = ''; | |
foreach ( (array) $q['search_terms'] as $term ) { | |
$term = esc_sql( $wpdb->esc_like( $term ) ); | |
$search .= "{$searchand}($wpdb->posts.post_title LIKE '{$x}{$term}{$x}')"; | |
$searchand = ' AND '; | |
} | |
if ( ! empty( $search ) ) { | |
$search = " AND ({$search}) "; | |
} | |
return $search; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment