我正在尝试使用自定义字段(ACF)的内容向我的自定义帖子类型添加新的管理列。我要添加的字段是一个“帖子对象”字段,但是它仅显示帖子标题,而不是ACF中的链接帖子。我添加了屏幕截图。
这是我到目前为止所拥有的:
function add_new_realisaties_column($columns) {
$columns['realisatie_line'] = 'Line';
return $columns;
}
add_filter('manage_realisaties_posts_columns', 'add_new_realisaties_column');
function add_new_realisaties_admin_column_show_value( $column, $post_id ) {
if ($column == 'realisatie_line') {
$post_object = get_field('realisatie_line');
if( $post_object ):
// override $post
$post = $post_object;
setup_postdata( $post );
$evdate = the_title();
wp_reset_postdata(); // IMPORTANT - reset the $post object so the rest of the page works correctly ?>
<?php endif;
echo $evdate;
}
}
add_filter('manage_realisaties_posts_custom_column', 'add_new_realisaties_admin_column_show_value', 10, 2);
/* Make the column sortable */
function set_custom_realisaties_sortable_columns( $columns ) {
$columns['realisatie_line'] = 'realisatie_line';
return $columns;
}
add_filter( 'manage_edit-realisaties_sortable_columns', 'set_custom_realisaties_sortable_columns' );
function realisaties_custom_orderby( $query ) {
if ( ! is_admin() )
return;
$orderby = $query->get('orderby');
if ( 'realisatie_line' == $orderby ) {
$query->set( 'meta_key', 'realisatie_line' );
$query->set( 'orderby', 'meta_value' );
}
}
add_action( 'pre_get_posts', 'realisaties_custom_orderby' );
答案 0 :(得分:1)
尝试将您的realisatie_line
函数更改为以下代码。如果ACF字段名称为$post_id
,则还需要传递function add_new_realisaties_admin_column_show_value( $column, $post_id ) {
//Try using a switch/case for the column name
switch ( $column ) {
case 'realisatie_line': //Name of new column from add_new_realisaties_column function
echo get_the_title( get_post_meta( $post_id, 'realisatie_line', true ) ); //Getting the ACF post meta using the $post_id, passing it through the get_the_title function to get title of attached post
break;
default:
break;
}
}
,以获取每个特定帖子的特定元数据。
{{1}}
答案 1 :(得分:1)
我注意到几件事。一个是您实际上不需要使用setup_postdata()
函数,因为ACF Post Object field使用get_post()
,它已经返回了完整的对象。仅当您打算覆盖全局$post
对象(例如在single-{post_type}.php
模板上说)时,才执行此操作。
另一件事是,对于帖子列,通常使用switch
语句而不是if/else
语句。有点书呆子,但要注意一点。
最后,the_title()
将在默认情况下回显标题,因此分配它,然后在以后回显它,可能会引起问题(即,变量在文档周围乱七八糟)。如果打算将其分配给变量,请考虑使用get_the_title()
。另外,我不会详细介绍细节,但是仅使用setup_postdata
可能不足以获取post helper函数从所需位置提取数据。
现在,尽管如此,您应该能够从get_field()
回显post_title
的{{1}}字段,因为它返回了full formed WP_Post object。我将其放在我的测试站点上,它按预期工作:
$post_object
这是管理员的样子,请注意,我刚刚在Post Object关系字段中抓了一条随机帖子: