I have two custom post types: Products and Brands. The Product slug is 'eproduct'. The Brand slug is 'brand-listing'. On the Product admin page, I have added a custom column that lists the Brand name. I am trying to make the "Brand" custom column sortable by the brand title (post_title of the Brand custom post type associated with that product). This is the code I have so far, using the posts_clauses
filter.
add_filter('posts_clauses', 'vendia_sort_brand_column',10,2);
function vendia_sort_brand_column( $clauses, $query ) {
global $wpdb;
if ( ! $query->is_main_query()
|| ! is_admin()
|| ! $query->get('post_type') == 'eproduct'
){
return $clauses;
}
$clauses['orderby'] = " {$wpdb->posts}.post_title ";
return $clauses;
}
As shown above, I have tried to modify the orderby
parameter of the SQL query, using the post_clauses
filter.
$clauses['orderby'] = " {$wpdb->posts}.post_title";
My stumbling block is that both the "Brand" and "Product" custom post types are in the wp_posts table. So {$wpdb->posts}.post_title
returns the Product title, not the Brand title that I am trying to order by. Thus, my Product admin page is simply sorted by Product title, not Brand title.
What I want to do is something like this
$clauses['orderby'] = " {$wpdb->posts}.post_title WHERE {$wpdb->posts}.post_type = 'brand-listing'";
The key change is that I have added WHERE {$wpdb->posts}.post_type = 'brand-listing'
to the ORDERBY
clause. However, apparently that is not valid SQL. My query returns 0 posts, and thus my Products admin screen lists no posts. I guess a WHERE
clause is not allowed inside an ORDERBY
clause? Or is it?
I am a novice to SQL, so I am wondering, what would be the valid SQL ORDERBY
clause to accomplish what I am trying to do?
I thank anyone who replies, for any help. I have been working on this for light years.