Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leobaiano/f835b9d9ff387ac2995f to your computer and use it in GitHub Desktop.
Save leobaiano/f835b9d9ff387ac2995f to your computer and use it in GitHub Desktop.
Filter Posts Search Admin WordPress - Custom Field
<?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