Skip to content

Instantly share code, notes, and snippets.

@tobiasschutter
Last active February 3, 2016 08:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tobiasschutter/ce77ec3aff6f4a62c028 to your computer and use it in GitHub Desktop.
Save tobiasschutter/ce77ec3aff6f4a62c028 to your computer and use it in GitHub Desktop.
Add custom fields for posts to the search in the wp-admin
<?php
/**
* Add custom fields for users to the search in the wp-admin
*/
function codepress_search_post_custom_fields( $wp ) {
global $pagenow, $wpdb;
// Fill in the post types that should be used
$post_types = array(
'post',
'page'
);
// Fill in the custom fields you want to add to the search
$custom_fields = array(
'my_custom_field_1',
'my_custom_field_2'
);
if ( 'edit.php' != $pagenow || empty( $wp->query['s'] ) || ( ! empty( $post_types ) && ! in_array( $wp->query_vars['post_type'], $post_types ) ) ) {
return;
}
// Search custom fields
$post_ids = $wpdb->get_col(
$wpdb->prepare( "
SELECT DISTINCT p1.post_id
FROM {$wpdb->postmeta} p1
INNER JOIN {$wpdb->postmeta} p2 ON p1.post_id = p2.post_id
WHERE ( p1.meta_key IN ('" . implode( "','", $custom_fields ) . "') AND p1.meta_value LIKE '%%%s%%' )
",
esc_attr( $_GET['s'] )
)
);
// so we know we're doing this
$wp->query_vars['custom_field_search'] = true;
// Search by found posts
$wp->query_vars['post__in'] = empty( $wp->query_vars['post__in'] ) ? $post_ids : array_merge( $wp->query_vars['post__in'], $post_ids );
}
add_action( 'parse_query', 'codepress_search_post_custom_fields', 11 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment