Recently i wanted to modify the Admin Columns for a Custom Post Type so it would be easier for my client to see the posts.
More specifically, i had a Custom Post Type named press
, for which i wanted to add 2 more custom fields, the Thumb and the Magazine date in the Admin list view, as you can see below:
Usually, i would use the manage_press_posts_columns
and manage_press_posts_custom_column
filters, BUT i did not want my columns to appear at the end. More specifically, i wanted the cover (thumb) of the magazine to appear right after the checkbox. So i had to place my custom fields in specific columns of the Admin Columns table.
Here is my solution:
function my_modify_press_table( $columns ) {
$columns = insertArrayAtPosition($columns, array('thumb' => 'Thumb'), 1); // add in second place ( after checkbox - array starts at 0)
$columns = insertArrayAtPosition($columns, array('press_date' => 'Mag. Date'), 3); //add as the 4th column (after the title)
return $columns;
}
add_filter( 'manage_press_posts_columns', 'my_modify_press_table' );
function my_modify_press_table_row( $column_name, $post_id ) {
$custom_fields = get_post_custom( $post_id );
switch ($column_name) {
case 'thumb' :
echo (isset($custom_fields['thumb'][0])) ? '<img src="'.get_field('thumb', $post_id).'" alt="tumb" style="width: 70px">' : ' ';
break;
case 'press_date' :
echo (isset($custom_fields['thumb'][0])) ? $custom_fields['press_date'][0] : ' ';
break;
default:
}
}
add_action( 'manage_press_posts_custom_column', 'my_modify_press_table_row', 10, 2 );
function insertArrayAtPosition( $array, $insert, $position ) {
//$array : The initial array i want to modify
//$insert : the new array i want to add, eg array('key' => 'value') or array('value')
//$position : the position where the new array will be inserted into. Please mind that arrays start at 0
return array_slice($array, 0, $position, TRUE) + $insert + array_slice($array, $position, NULL, TRUE);
}
So, i normally hook on the manage_press_posts_columns
and manage_press_posts_custom_column
filters as i would, however in the my_modify_press_table
function i place my two custom fields in the order that i want, simply by using the insertArrayAtPosition
function.
More on the 2 hooks used:
http://hookr.io/actions/manage_posts_custom_column/
http://hookr.io/4.7.4/filters/manage_posts_columns/
Hope you may find it usefull.