[SOLVED] Add a Custom Column in Custom Post Types Admin Screen Displaying Relational Data From Another Custom Post Type

September 14, 2016

I had a situation recently with WordPress where I had to display the Company Name against the Attendee profile when viewing a list of Attendees inside the WordPress admin.

Basically there was two custom post types (CPT’s), one was called “attendee” and the other “companies”. When editing an Attendee record we would assign it to a company so that we knew which Company the Attendee was assigned to.

After some ideas from the Advanced WordPress forum on Facebook, this is what I ended up with and code is included below.

custom-column-in-custom-post-type-admin-screen

Here is the code which I inserted into the themes functions.php to display the company name against the attendee record.

###################################################
//Creates a new column in your CPT admin which displays the post title of a related post
//USAGE: drop these functions and filters into your functions.php file
###################################################

//GET COMPANY NAME FROM POST TITLE
function attendee_screen_get_company_name($company_id) {
   
   $company_name = get_the_title($company_id);
   return $company_name;
 
}
 
//ADD NEW COLUMN TO ADMIN
function attendee_screen_columns_head($defaults) {
   
   $defaults['company_name'] = 'Company Name';
   return $defaults;
 
}
 
// SHOW THE CONTENT OF THE COMPANY NAME COLUMN
function attendee_screen_columns_content($column_name, $post_id) {
 
   if ($column_name == 'company_name') {
   $company_id = get_post_meta( $post_id, "company_id", $single = true );
    if ($company_id) {
      $company_name = attendee_screen_get_company_name($company_id);
    }
    if ($company_name) {
    echo '<a href="post.php?post='.$company_id.'&action=edit" data-mce-href="post.php?post='.$company_id.'&action=edit">'.$company_name .'</a>';
    } else {
    echo "";
    }
 
  }
 
}
 
// HOOK INTO WORDPRESS TO GET IT ALL WORKING
add_filter('manage_attendee_posts_columns', 'attendee_screen_columns_head', 10);
add_action('manage_attendee_posts_custom_column', 'attendee_screen_columns_content', 10, 2);