Code that works to create new column in Wordpress admin for post list:
//adds new column to posts list in Wordpress admin
add_filter( 'manage_posts_columns', 'set_custom_edit_mycpt_columns' );
function set_custom_edit_mycpt_columns( $columns ) {
$columns['acf_field'] = __( 'Editorial status', 'my-text-domain' );
return $columns;
}
// pulls label from ACF Pro select field into new column for each post
add_action( 'manage_posts_custom_column' , 'custom_mycpt_column', 10, 2 );
function custom_mycpt_column( $column, $post_id ) {
switch ( $column ) {
// display the value of an ACF (Advanced Custom Fields) field
case 'acf_field' :
$ed_status = get_field_object( 'ed_status_acf', $post_id );
$ed_status_pretty = $ed_status['label'];
echo $ed_status_pretty;
break;
}
}
The problem: I'm successfully pulling in labels from the select field that I created in Advanced Custom Fields Pro from each post and seeing those labels populate in the 'Editorial status' column. (See working portion of code above.) What I'm not able to figure out is how to make that column sortable, despite trying different tutorials.
The non-working portion of the code appears below. This code doesn't break the site — the column simply remains unsortable.
// make new column sortable by ACF field
add_filter( 'manage_edit-posts_sortable_columns', 'set_custom_mycpt_sortable_columns' );
function set_custom_mycpt_sortable_columns( $columns ) {
$columns['custom_taxonomy'] = 'custom_taxonomy';
$columns['acf_field'] = 'acf_field';
return $columns;
}
// give parameters to Wordpress for sorting the new column
add_action( 'pre_get_posts', 'mycpt_custom_orderby' );
function mycpt_custom_orderby( $query ) {
if ( is_admin() ) {
return;
$orderby = $query->get( 'orderby');
if ( 'acf_field' == $orderby ) {
$query->set( 'meta_key', 'acf_field' );
$query->set( 'orderby', 'meta_value' );
}
}
}
The goal: Figure out what I'm doing wrong and make the 'Editorial status' column that appears on the post list page in Wordpress admin sortable. I'd like to be able to sort alphabetically by editorial status (e.g., draft, pending, under review, etc.)
All code above is currently in a custom plugin that I created. I've seen solutions that work when ACF Pro select fields aren't used, so I have a feeling it has to do with pre_get_posts
and using the meta from the select with get_field_object
, but I'm not sure.
Any feedback appreciated, since I can't figure out where I'm going wrong! I know there are plugins to create custom sortable columns for Wordpress. I'd like to know what I'm doing wrong here, however, in order to learn. Thanks!