Created
March 5, 2015 15:28
-
-
Save jjeaton/41eedccdd5256cf756ec to your computer and use it in GitHub Desktop.
Search by post slug in the WP Admin
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
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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks. Very useful.