Menu Close

Adding ACF Fields as Admin Columns to your CPT


We all know how awesome Advanced Custom Fields (ACF) is right? We pretty much use the Pro version of it on every WordPress website build we do.

Today, we are going to show you how to add fields to your CPT (Custom Post Type) to the backend Admin Columns.

There are a few plugins that can accomplish adding your ACF fields as admin columns to the backend. Admin Columns is one of the best ones that does the trick. The paid version allows your custom post type to connect with ACF Pro.

As programmers, we want to keep the number of plugins we use to a minimum right? well, it’s pretty simple to add these manually!

Okay, so here we go… Let’s say that you have created a post type, ‘hosting’, and two custom meta fields, ‘start_date’ and ‘end_date’. You’d like to add both meta fields to the custom post type list view. First of all, we will need to add the following to the functions.php file:-

 *	ACF Admin Columns

 function add_acf_columns ( $columns ) {
   return array_merge ( $columns, array ( 
     'start_date' => __ ( 'Starts' ),
     'end_date'   => __ ( 'Ends' ) 
   ) );
 add_filter ( 'manage_hosting_posts_columns', 'add_acf_columns' );

This filter adds your additional columns to the list. We have created an array containing two items – one for the start date and one for the end date – and merged it with the existing columns. The filter is hooked to the specific post type, in this case, manage_hosting_posts_columns, based on the format manage_POSTTYPE_posts_columns. You’ll need to edit this filter to match your custom post type slug.

Secondly, add the following code to output the meta field values:-

 * Add columns to Hosting CPT
 function hosting_custom_column ( $column, $post_id ) {
   switch ( $column ) {
     case 'start_date':
       echo get_post_meta ( $post_id, 'hosting_start_date', true );
     case 'end_date':
       echo get_post_meta ( $post_id, 'hosting_end_date', true );
add_action ( 'manage_hosting_posts_custom_column', 'hosting_custom_column', 10, 2 );

Again, notice how the action hook is specific to your post type, in this case, manage_hosting_posts_custom_column. The function looks for the name of your custom columns then echoes the metadata.

Awesome, we’ve added the fields now! But wait, do you want to go the extra step and make the fields sortable? Of course, why wouldn’t you! Here’s how we can do that:-

 * Add Sortable columns

function my_column_register_sortable( $columns ) {
	$columns['start_date'] = 'start_date';
	$columns['end_date'] = 'start_date';
	return $columns;
add_filter('manage_edit-hosting_sortable_columns', 'my_column_register_sortable' );

Well, we hope you have found this tutorial usual, be sure to leave a comment if this has helped you or if you require any help!

View Source
Posted in WordPress