We have two custom fields(ACF) for a News post type – oEmbed and link. We added the custom columns in the WP admin, but the sorting doesn’t work properly.
Here is the code we tried for sorting:
add_action( 'pre_get_posts', 'custom_orderby' );
function custom_orderby( $query ) {
if( ! is_admin() )
return;
$orderby = $query->get( 'orderby');
if( 'video' == $orderby ) {
$query->set('meta_key','video');
$query->set('orderby','meta_value');
}
}
We also tried with this:
$query->query_orderby = "ORDER BY ( SELECT meta_value FROM wp_postmeta posts WHERE posts.meta_key = 'video' ) {$order}";
But it didn’t work.
Iām not an expert on this but I did something similar – added columns for a CPT and made them sortable……so a couple of suggestions (questions?) come to mind:
1. I assume you specified that the (new) columns are sortable using the hook “manage_edit-{cpt}_sortable_columns’? I have three added columns for a ‘deals’ CPT so I made those columns sortable like this (example):
function my_deal_sortable_columns( $columns ) {
$columns['expires'] = 'expires';
$columns['author'] = 'author';
$columns['resort'] = 'resort';
return $columns;
}
add_filter( 'manage_edit-deal_sortable_columns', 'my_deal_sortable_columns' );
2. Perhaps you need to add the meta_type to your orderby statement? I need the ‘expires’ column to be sortable based on the value which is a date, not a string, so I had to add the meta_type, like this example:
$orderby = $query->get( 'orderby');
if( 'expires' == $orderby ) {
$query->set('meta_key','booking_date_end');
$query->set('orderby','meta_value');
$query->set('meta_type','DATE');
$query->set('ignore_sticky_posts',true);
}
Hopefully this may be enough to help, if not post back and maybe I can be of more assistance. Good luck!
Thanks, this worked!
We have ended up with this code(I don’t know why is working):
add_filter( 'manage_edit-news_sortable_columns', 'set_custom_news_sortable_columns' );
function set_custom_news_sortable_columns( $columns ) {
$columns['iframe'] = 'iframe';
$columns['video'] = 'video';
return $columns;
}
if( 'video' == $orderby ) {
$query->set('meta_key','video');
$query->set('orderby','meta_value');
$query->set('meta_type','video');
$query->set('ignore_sticky_posts',true);
}
Likely the addition of the meta_type, but YAY! I’m glad it’s working for you! š