I have a custom post type for books that has two ACF fields, book_title
and book_author
. I have a separate custom post type for passages from the book, which pulls in a book, as an ACF post object, into two fields in the passages custom post type with the same field names.
I would like to be able to display the book_title
and book_author
fields as columns in the passages custom post type list. I am currently able to pull in the title of the book, but thats only because I am grabbing the title of the post, not the actual book_title
field from the post. Is there a way to grab fields from a post object like this and set them as columns?
Here is my current code from my passages custom post type file:
function add_acf_columns($columns)
{
return array_merge($columns, array(
'book_title' => __('Book Title') ,
'book_author' => __('Book Author')
));
}
add_filter('manage_passages_posts_columns', 'add_acf_columns');
function passages_custom_column($column, $post_id)
{
switch ($column)
{
case 'book_title':
echo get_the_title(get_field('book_title', $post_id));
break;
case 'book_author':
echo get_post_meta($post_id, 'book_author', true);
break;
}
}
add_action('manage_passages_posts_custom_column', 'passages_custom_column', 10, 2);
I solved this by modifying Xhynk's answer.
After you grab the ID of the Book post object in the Passages post book
field, you can use ACF's get_field() to grab the title
and author
values from the Book post itself, and then pass those values into the columns.
// add columns to passages list
add_filter('manage_passages_posts_columns', 'add_acf_columns');
function add_acf_columns($columns)
{
return array_merge($columns, array(
'book_title' => __('Book Title') ,
'book_author' => __('Book Author')
));
}
// add title and author to passages list columns
add_action('manage_passages_posts_custom_column', 'passages_custom_column', 10, 2);
function passages_custom_column($column, $post_id) {
switch( $column ){
case 'book_title':
$book_object = get_field( 'book', $post_id );
$book_title = get_field('title', $book_object->ID);
echo ($book_title) ? $book_title : '';
break;
case 'book_author':
$book_object = get_field( 'book', $post_id );
$book_author = get_field('author', $book_object->ID);
echo ($book_author) ? $book_author : '';
break;
}
}