Created
July 22, 2015 21:31
-
-
Save leobaiano/f835b9d9ff387ac2995f to your computer and use it in GitHub Desktop.
Filter Posts Search Admin WordPress - Custom Field
This file contains 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 | |
function my_admin_post_search_by_custom_fields( $query ) { | |
if ( ! is_admin() ) { | |
return; | |
} | |
// Search just for posts | |
if ( isset( $query->query_vars['post_type'] ) && 'post' !== $query->query_vars['post_type'] ) { | |
return; | |
} | |
if ( ! empty( $query->query_vars['s'] ) ) { | |
$term = $query->query_vars['s']; | |
$custom_fields = array( 'my_custom_field' ); // Set here your custom fields for search | |
$meta_query = array( 'relation' => 'OR' ); | |
foreach ( $custom_fields as $field ) { | |
array_push( $meta_query, array( | |
'key' => $field, | |
'value' => $term, | |
'compare' => 'LIKE' | |
) ); | |
} | |
$query->set( 'meta_query', $meta_query ); | |
// Exclude regular search | |
unset( $query->query_vars['s'] ); | |
} | |
} | |
add_filter( 'pre_get_posts', 'my_admin_post_search_by_custom_fields' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment