You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将帖子中的多个ACF用户字段合并到另一字段?

问题描述

我在帖子中配置了若干可选择用户的ACF用户字段,希望将其中两个字段(contractor、architect)的内容合并到第三个字段(project_user_select)中,使前两个字段中的用户都显示在第三个字段内。字段的返回格式为用户数组,以下是我当前的尝试代码:

add_action( 'acf/save_post', 'my_acf_save_post', 10 );
function my_acf_save_post( $post_id ) {
    // Get value of field 1
    $value1 = get_field( 'contractor', $post_id );
    // Get value of field 2 
    $value2 = get_field( 'architect', $post_id );

    update_field( 'project_user_select', $value1 . $value2, $post_id );
}
解决方案

你的代码核心问题是误用了字符串拼接运算符.来合并数组,这会把用户数组强制转换成字符串后拼接,完全不符合ACF用户字段要求的数组格式。正确做法是用数组合并函数处理,同时优化逻辑避免异常情况,代码如下:

add_action( 'acf/save_post', 'merge_acf_user_fields', 10 );
function merge_acf_user_fields( $post_id ) {
    // 跳过自动保存和修订版,避免重复执行
    if ( wp_is_post_autosave( $post_id ) || wp_is_post_revision( $post_id ) ) {
        return;
    }

    // 获取字段值,为空时默认设为空数组,防止合并时出错
    $contractors = get_field( 'contractor', $post_id ) ?: [];
    $architects = get_field( 'architect', $post_id ) ?: [];

    // 合并两个用户数组,同时去重(避免同一用户被两个字段选中时重复显示)
    $merged_users = array_unique( array_merge( $contractors, $architects ), SORT_REGULAR );

    // 更新目标字段,建议替换成project_user_select对应的ACF字段键(如field_xxxxxx),稳定性更高
    update_field( 'project_user_select', $merged_users, $post_id );
}

关键说明

  • 数组合并逻辑:用array_merge()替代字符串拼接,确保输出是ACF需要的用户数组格式
  • 空值处理:通过?: []给未选择用户的字段设置默认空数组,避免null导致的合并错误
  • 去重优化:array_unique(..., SORT_REGULAR)可以移除重复的用户对象,避免同一用户重复出现在目标字段中
  • 跳过无效保存:添加自动保存和修订版判断,减少不必要的字段更新操作
  • 字段键优化:ACF官方推荐使用字段键(而非字段名)调用update_field,你可以在ACF字段编辑页的「帮助」标签下找到对应字段键,替换后更稳定

内容的提问来源于stack exchange,提问作者Webbb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 15:10:22