ACF user字段关联用户时无法调用short-description自定义字段
ACF关联用户后无法调用用户自定义字段的解决方法
问题复现
使用ACF的user字段给文章关联对应用户,关联用户提前配置了short-description自定义字段。
现有代码可以正常输出用户名,但无法输出short-description字段内容:
<?php $user = get_field("seller"); if( $user ): ?> <h3><?php echo $user['display_name']; ?></h3> <?php the_field('short-description'); ?> <?php endif; ?>
尝试传入$user作为the_field第二个参数依旧无效:
<?php the_field('short-description', $user); ?>
错误原因
- 第一种写法未指定读取上下文,
the_field默认读取当前文章的自定义字段,而short-description存储在用户元数据中,无法被读取。 - 第二种写法传参格式错误:ACF读取用户类型的自定义字段时,第二个参数要求传入
user_+用户ID的字符串格式,不能直接传入整个用户数组或者用户对象。
修正代码
你当前使用的是ACF user字段默认的「返回用户数组」配置,直接从数组中取出用户ID,拼接前缀传入即可正常输出:
<?php $user = get_field("seller"); if( $user ): ?> <h3><?php echo $user['display_name']; ?></h3> <?php the_field('short-description', 'user_' . $user['ID']); ?> <?php endif; ?>
如果你后续修改了user字段的返回格式,可参考对应写法:
- 返回格式为用户ID时:
<?php $user_id = get_field("seller"); if( $user_id ): ?> <h3><?php echo get_the_author_meta('display_name', $user_id); ?></h3> <?php the_field('short-description', 'user_' . $user_id); ?> <?php endif; ?>
- 返回格式为WP_User对象时:
<?php $user = get_field("seller"); if( $user ): ?> <h3><?php echo $user->display_name; ?></h3> <?php the_field('short-description', 'user_' . $user->ID); ?> <?php endif; ?>
内容的提问来源于stack exchange,提问作者Åsmund Sollihøgda
相关产品推荐
相关产品推荐

