Search & column order by meta value in admin
So, my posts have a custom field named company and I would like to have a sortable column for this field in the admin area list of posts and also be able to search posts by it's content.
I've been able to do both things but not at the same time. That is: the search works but when I try to order it by the company column it goes blank. If I don't do a search, the ordering works fine
This is my function to search in the meta field:
//add metas to the search
add_filter('posts_clauses', 'my_admin_search_clauses',11,2);
function my_admin_search_clauses( $clauses, $query )
{
global $wpdb, $wp;
$like = '%' . $wpdb-esc_like( $wp-query_vars['s'] ) . '%';
$where = str_replace( ($wpdb-posts.post_excerpt LIKE, ($wpdb-postmeta.meta_value LIKE '$like' AND $wpdb-postmeta.meta_key = 'company') OR ($wpdb-posts.post_excerpt LIKE, $clauses['where'] );
$clauses['join'] .= LEFT JOIN $wpdb-postmeta ON ($wpdb-posts.ID = $wpdb-postmeta.post_id) ;
$clauses['groupby'] = $wpdb-posts.ID;
$clauses['where'] = $where;
return $clauses;
}
And this is the code to make the column (previously added with other filters and actions) sortable:
//sort by column
add_filter( 'request', 'company_column_orderby' );
function company_column_orderby( $vars ) {
if ( isset( $vars['orderby'] ) 'company' == $vars['orderby'] ) {
$vars = array_merge( $vars, array(
'meta_key' = 'company',
'orderby' = 'meta_value',
'order' = isset($vars['order'])?$vars['order']:'asc'
) );
}
return $vars;
}
I think the problem is related to conflicting joins, but I can't find the way to make it work in all situations