Admin Search Posts with Custom Post Meta – WordPress
Advertisement
Have you ever wanted to be able to search post by using post-meta, how handy would that be? We all know that adding custom post-meta column and make it sortable is possible, just by using WordPress provided hook and filter and we’re done, as so with this snippet we only need three filters hook and we’re good to go.
Let’s get started.
Just add this below code to your current theme functions.php
file.
add_filter( 'posts_join', 'posts_join_func' );
add_filter( 'posts_where', 'posts_where_func' );
add_filter( 'posts_groupby', 'posts_groupby_func' );
/**
* Join for searching metadata
*/
function posts_join_func( $join ) {
global $wpdb;
if ( ! is_applicable() )
return $join;
$join .= "LEFT JOIN $wpdb->postmeta ON $wpdb->posts.ID = $wpdb->postmeta.post_id ";
return $join;
}
/**
* Make sure we got the specific search result
*/
function posts_where_func( $where, &$wp_query ) {
global $wpdb, $wp;
if ( ! is_applicable() )
return $where;
$where = preg_replace(
"/($wpdb->posts.post_title LIKE '%{$wp->query_vars['s']}%')/i",
"$0 OR $wpdb->postmeta.meta_value LIKE '%{$wp->query_vars['s']}%' ",
$where
);
return $where;
}
/**
* Group result by post ID to make sure that we didn't get duplicate result
*/
function posts_groupby_func( $groupby ) {
global $wpdb;
if ( ! is_applicable() )
return $groupby;
if ( empty( $groupby ) )
$groupby = "$wpdb->posts.ID";
return $groupby;
}
/**
* Make sure we're on the correct page
*/
function is_applicable() {
global $pagenow, $wp_query;
// check if we're in admin area
if ( ! is_admin() )
return false;
// check if we're in post edit page
if ( 'edit.php' != $pagenow )
return false;
// cehck if search term is set
if ( ! isset( $_GET['s'] ) )
return false;
// check if we're in search page
if ( ! $wp_query->is_search )
return false;
return true;
}
That’s it, happy coding ^_^
Advertisement