ACF多关系查询框优化:在Summit名称旁显示Location
修正ACF Relationship字段显示关联Location的代码问题
原代码的核心问题在于变量访问语法错误,且缺少关联数据的有效性校验,同时未考虑ACF字段的不同返回设置。以下是修正后的完整代码:
add_filter('acf/fields/relationship/result/name=sommet_rel', 'id_relationship_result', 10, 4); function id_relationship_result($title, $post, $field, $post_id){ // 获取当前Summit关联的Location $location = get_field('location', $post->ID); // 先判断Location是否存在,避免报错 if ($location) { // 处理ACF字段返回Post对象的情况 if (is_object($location)) { $title .= ' (' . $location->post_title . ')'; } // 处理ACF字段返回Post ID的情况 elseif (is_numeric($location)) { $location_post = get_post($location); if ($location_post) { $title .= ' (' . $location_post->post_title . ')'; } } } return $title; }
关键修正点说明:
- 修复变量访问错误:原代码
$location->$post_title是错误写法,正确的对象属性访问应为$location->post_title(无需额外加$符号)。 - 增加空值校验:通过
if ($location)确保仅当存在关联Location时才拼接内容,避免PHP警告。 - 兼容两种返回类型:ACF的Post Object/Relationship字段可设置返回「对象」或「ID」,代码同时处理这两种情况,提升兼容性。
- 优化显示格式:用括号包裹Location名称,让Summit与Location的区分更直观,例如显示为「勃朗峰 (法国)」。
额外检查项:
- 确认Summit的ACF字段键确实是
location(ACF字段键为小写无空格格式)。 - 若使用Post Object类型字段,确保ACF设置中「返回格式」选择的是「Post对象」或「Post ID」,代码均可兼容。
内容的提问来源于stack exchange,提问作者f.soucy
相关产品推荐
相关产品推荐

