Skip to content

Instantly share code, notes, and snippets.

@jjeaton
Created March 5, 2015 15:28
Show Gist options
  • Save jjeaton/41eedccdd5256cf756ec to your computer and use it in GitHub Desktop.
Save jjeaton/41eedccdd5256cf756ec to your computer and use it in GitHub Desktop.
Search by post slug in the WP Admin
add_filter( 'posts_search', 'jje_search_by_slug', 10, 2 );
/**
* Add post slugs to admin search for a specific post type
*
* Rebuilds the search clauses to include post slugs.
*
* @param string $search
* @param WP_Query $query
* @return string
*/
function jje_search_by_slug( $search, $query ) {
global $wpdb;
// Only run if we're in the admin and searching our specific post type
if ( $query->is_search() && $query->is_admin && 'wire-product' === $query->query_vars['post_type'] ) {
$search = ''; // We will rebuild the entire clause
$searchand = '';
foreach ( $query->query_vars['search_terms'] as $term ) {
$like = '%' . $wpdb->esc_like( $term ) . '%';
$search .= $wpdb->prepare( "{$searchand}(($wpdb->posts.post_title LIKE %s) OR ($wpdb->posts.post_content LIKE %s) OR ($wpdb->posts.post_name LIKE %s))", $like, $like, $like );
$searchand = ' AND ';
}
if ( ! empty( $search ) ) {
$search = " AND ({$search}) ";
if ( ! is_user_logged_in() )
$search .= " AND ($wpdb->posts.post_password = '') ";
}
}
return $search;
}
@selasphorus
Copy link

Thanks. Very useful.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment