添加包含元字段(ACF)内容的分类列

时间:2021-04-30 作者:aitor

尝试用元字段填充列,方法如下(ACF):

add_filter(\'manage_artist_custom_column\', function ($content,$column_name,$term_id){
    $term= get_term($term_id, \'artist\');
    switch ($column_name) {
        case \'artist_avatar\':
            $avatar = get_field(\'artist_avatar\', $term);
            var_dump($avatar);
            $content = $avatar[\'url\'];
            break;
        default:
            break;
    }
    return $content;
},10,3);

add_filter( \'manage_edit-artist_columns\', function ( $columns ) {
    $columns[\'artist_avatar\'] = __(\'Artist Avatar\', \'sage\');
    return $columns;
} );
当我var_dump($avatar); 我得到输出:

array(24) {
  ["ID"]=>
  int(315)
  ["id"]=>
  int(315)
  ["title"]=>
  string(16) "bigote-sucio-pic"
  ["filename"]=>
  string(20) "bigote-sucio-pic.jpg"
  ["filesize"]=>
  int(238431)
  ["url"]=>
  string(66) "https://futurabasura.test/app/uploads/2021/04/bigote-sucio-pic.jpg"
  etc …
  etc …
但是,如果我尝试访问任何阵列密钥:

$content = $avatar[\'url\'];
我明白了"Trying to access array offset on value of type bool"

为什么?

1 个回复
SO网友:aitor

正如Sally CJ在评论中指出的那样,错误来自artist_avatar空的那么,检查一下is_array() 在访问阵列之前,请先修复它:

add_filter(\'manage_artist_custom_column\', function ($content,$column_name,$term_id){
    $term = get_term($term_id, \'artist\');
    $avatar = get_field(\'artist_avatar\', $term);

    switch ($column_name) {
        case \'artist_avatar\':
            if ( is_array( $avatar ) ) {
                $content = $avatar["url"];
            } else {
                $content = __(\'This artist has no picture\', \'sage\');
            }
            break;
        default:
            break;
    }
    return $content;
},10,3);

相关推荐

Get full image array

当我使用高级自定义字段时,我可以返回上载的完整图像数组。是否有本机WordPress方法可以通过图像ID获取媒体库中任何图像的完整图像阵列?我可以找到方法来获取alt文本和特定的图像大小,但不能获取数组本身。。。