关联用户的ACF图片字段调用update_field更新失败是什么原因?
核心错误点
- ACF图片字段存储规则不符:无论后台设置的返回值格式是图片URL、数组还是ID,ACF的图片字段底层存储的都是附件ID,你传入图片URL无法被ACF识别,导致字段更新失败。
- 附件注册流程不完整:调用
wp_insert_attachment()插入附件时缺少文件路径参数,且插入后没有生成图片的元数据(缩略图、尺寸信息等),附件属于未完成注册的状态,即便传ID也可能出现异常。 - 用户字段标识格式错误:如果
foto-agente是用户的自定义字段,update_field的第三个参数不能直接传用户ID或用户对象,需要按照user_<用户ID>的格式拼接参数,比如用户ID为12则传user_12。
修正后的代码示例
$wp_upload_dir = wp_upload_dir(); $filename_path = $wp_upload_dir['path'] . "/$img"; $filename_url = $wp_upload_dir['url'] ."/$img"; $wp_filetype = wp_check_filetype(basename($filename_path), null ); $attachment = array( 'guid'=> $wp_upload_dir['url'] . '/' . basename( $filename_path ), 'post_mime_type' => $wp_filetype['type'], 'post_title' => $img, 'post_content' => '', 'post_status' => 'inherit' ); // 插入附件,补全文件路径参数 $attach_id = wp_insert_attachment( $attachment, $filename_path ); // 引入图片处理依赖,生成并更新附件元数据 require_once( ABSPATH . 'wp-admin/includes/image.php' ); $attach_data = wp_generate_attachment_metadata( $attach_id, $filename_path ); wp_update_attachment_metadata( $attach_id, $attach_data ); // 拼接用户字段标识,若$user是用户对象则替换为 $user->ID $user_field_key = 'user_' . $user; // 传入附件ID更新ACF字段,后台设置返回格式为URL的前提下,前端get_field会自动返回图片链接 update_field('foto-agente', $attach_id, $user_field_key);
内容的提问来源于stack exchange,提问作者Micki Benci
相关产品推荐
相关产品推荐

