Skip to content

Instantly share code, notes, and snippets.

@hauge75
Created October 7, 2022 21:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hauge75/d124cdab69fb0343b1cf927542da0f98 to your computer and use it in GitHub Desktop.
Save hauge75/d124cdab69fb0343b1cf927542da0f98 to your computer and use it in GitHub Desktop.
Display Sortabel ACF Post Object field in admin column
/*
* Add columns to post list
*/
function add_acf_columns ( $columns ) {
return array_merge ( $columns, array (
'custom_column' => __ ( 'Custom column' ),
) );
}
add_filter ( 'manage_postname_posts_columns', 'add_acf_columns' );
/*
* Add columns to Hosting CPT
*/
function add_custom_column ( $column, $post_id ) {
switch ( $column ) {
case 'custom_column':
$position = get_field( 'field_name', $post_id );
echo $position;
break;
}
}
add_action ( 'manage_postname_posts_custom_column', 'add_custom_column', 10, 2 );
add_filter('manage_postname_posts_columns', 'column_order');
function column_order($columns) {
$n_columns = array();
$move = 'custom_column'; // what to move
$before = 'date'; // move before this
foreach($columns as $key => $value) {
if ($key==$before){
$n_columns[$move] = $move;
}
$n_columns[$key] = $value;
}
return $n_columns;
}
add_filter( 'manage_edit-postname_sortable_columns', 'my_sortable_custom_column' );
function my_sortable_custom_column( $columns ) {
$columns['custom_column'] = 'custom_column';
//To make a column 'un-sortable' remove it from the array
//unset($columns['custom_column']);
return $columns;
}
add_action( 'pre_get_posts', 'my_custom_column_orderby' );
function my_custom_column_orderby( $query ) {
if( ! is_admin() )
return;
$orderby = $query->get( 'orderby');
if( 'custom_column' == $orderby ) {
$query->set('meta_key','field_name');
$query->set('orderby','meta_value_num'); // if numeric
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment