ACF:无法从帖子循环中的关系字段 Post 对象获取标题



我正试图使用ACF字段在管理页面中设置一个自定义列。该字段是一个关系字段,但是我总是出错。我的函数内部代码.pp:

function my_product_columns($columns)
{
$columns = array(
'cb'        => '<input type="checkbox" />',
'title'     => 'Name',
'artist'    => 'Artist',
'media'     =>  'Media',
);
return $columns;
}
function my_product_artist_columns($column)
{
global $post;
$post_id = $post->ID;
if ($column == 'artist') {
$artist_field = get_field( "product_artist", $post_id);
echo $artist_field->post_title; //THIS IS THE PROBLEM!
}
else {
echo '';
}
}

有了这个,我得到以下错误消息:

注意:正在尝试获取中非对象的属性"post_title">

如果我执行echo $artist_field['post_title'];,我会得到:

致命错误:未捕获错误:无法将WP_Post类型的对象用作中的数组

print_r($artist_field);给了我:WP_Post对象

WP_Post Object (
[ID] => 778
[post_author] => 1
[post_date] => 2018-12-06 09:18:26
[post_date_gmt] => 2018-12-06 09:18:26
[post_content] => This is Solomon
[post_title] => Solomon Northup
[post_excerpt] => 
[post_status] => publish
[comment_status] => closed
[ping_status] => closed
[post_password] => 
[post_name] => solomon-northup
[to_ping] => 
[pinged] => 
[post_modified] => 2018-12-06 09:18:26
[post_modified_gmt] => 2018-12-06 09:18:26
[post_content_filtered] => 
[post_parent] => 0
[guid] => http://localhost:8888/swart.shop/wp/?post_type=artists&p=778
[menu_order] => 0
[post_type] => artists
[post_mime_type] => 
[comment_count] => 0
[filter] => raw
)

是因为它是后循环中的后循环吗?我该如何修复它?

我找到了答案:https://support.advancedcustomfields.com/forums/topic/use-post-object-in-a-loop-of-a-custom-post-type/

我的代码是:

if ($column == 'artist') {
$post_object = get_field( "product_artist"); if( $post_object ) {   
$post = $post_object; setup_postdata( $post );  //Call the post object Inside and work with
the_title();
$post = $post_id; setup_postdata( $post ); ////Call back the "parent" post datas
} else {
echo '';
}
}
else {
echo '';
}

最新更新