Sortable Admin Columns with Advanced Custom Fields ACF

Add Advanced Custom Fields ACF to your admin columns in WordPress and be able to sort them.

For this I will add a custom thumbnail and Event start date for an “Event” Custom post type.

First, you need two functions. One to create the columns, overriding what was default in WordPress and one to tell what each column to do.

/*-------------------------------------------------------------------------------
	Custom Columns
-------------------------------------------------------------------------------*/

function my_page_columns($columns)
{
	$columns = array(
		'cb' 	=> '<input type="checkbox" />',
                'title' 	=> 'Title',
		'thumbnail'	=> 'Thumbnail',
		'event' 	=> 'Event Date',
		//'author'	=> 'Author',
		//'date'	=> 'Date',
	);
	return $columns;
}

function my_custom_columns($column)
{
	global $post;
	if($column == 'event')
	{
	   $date = DateTime::createFromFormat('Ymd', get_field('event_date'));
	   if( empty( $date ) ) :
	     echo 'No Date';
	   else:
	     echo $date->format('M/d/Y');
	   endif;

	} elseif ($column == 'thumbnail'){
	   $image = get_field('event_image');
	   $size = 'thumbnail';
	   $thumb = $image['sizes'][ $size ];
	   echo '<img src="'.$thumb.'" />';
	}
}

add_action("manage_event_posts_custom_column", "my_custom_columns");
add_filter("manage_edit-event_columns", "my_page_columns");

It’s important to note that the structure of the add_action:  ‘manage_{YOUR_POSTTYPE}_posts_custom_column’
and the structure of the filter ‘manage_edit-{YOUR_POSTTYPE}_columns’

Then this final function to sort by Event Date:

function my_column_register_sortable( $columns )
{
	$columns['event'] = 'event';
	return $columns;
}

add_filter("manage_edit-event_sortable_columns", "my_column_register_sortable" );

Again, note the structure of the filter:
‘manage_edit-{YOUR_POSTTYPE}_event_sortable_columns’

2 thoughts on “Sortable Admin Columns with Advanced Custom Fields ACF

  1. Nathan Robinson

    How would you go about sorting by the title of a post object? In my case, I’m using ACF to reference another Custom Post Type, but as far as I can tell, the only meta value that’s stored in the ACF field is the ID of the Custom Post. So when sorting the admin column, it sorts according to the value of the Custom Post’s ID and not by the Custom Post’s title.

    Any help would be appreciated!

  2. Pip

    Hi,
    I got this working but I would like to ad a columns that holds the fields of a post_object field.
    How do I do this?

    Regards

Leave a Reply

Your email address will not be published. Required fields are marked *

5 + 2 =