WordPress/Fluent Form/ACF实现用户单Profile帖子的创建与更新
实现登录用户专属ACF CPT Profile的Fluent Form单例编辑功能
核心思路
- 检测当前登录用户是否已拥有
Profile类型文章 - 存在则自动加载该文章的ACF字段值到表单
- 表单提交时,根据是否存在已有文章,动态执行创建或更新操作
1. 后端:获取用户专属Profile文章ID
在主题的functions.php中添加以下函数,用于查询当前用户的唯一Profile文章:
function get_user_profile_post_id($user_id = null) { if (!$user_id) { $user_id = get_current_user_id(); } if (!$user_id) return false; $args = [ 'post_type' => 'profile', // 替换为你的自定义文章类型名称 'post_status' => 'publish', 'author' => $user_id, 'posts_per_page' => 1, 'fields' => 'ids' ]; $posts = get_posts($args); return !empty($posts) ? $posts[0] : false; }
2. 前端:自动填充表单已有数据
通过Fluent Form的钩子,在表单渲染时将用户已有的ACF字段值填充到对应表单控件中(需确保表单字段name与ACF字段键一致):
add_filter('fluentform/rendering_field_data', 'populate_profile_form_fields', 10, 3); function populate_profile_form_fields($field, $formId, $formData) { $target_form_id = 123; // 替换为你的目标表单ID if ($formId != $target_form_id) return $field; $user_id = get_current_user_id(); if (!$user_id) return $field; $profile_post_id = get_user_profile_post_id($user_id); if (!$profile_post_id) return $field; $acf_value = get_field($field['name'], $profile_post_id); if ($acf_value) { $field['value'] = $acf_value; } return $field; }
3. 表单提交:动态创建/更新Profile文章
在表单提交时,判断用户是否已有Profile,执行对应的创建或更新操作,并同步ACF字段值:
add_action('fluentform/submission_confirmation', 'handle_profile_form_submission', 10, 4); function handle_profile_form_submission($confirmation, $formData, $entry, $form) { $target_form_id = 123; // 替换为你的目标表单ID if ($form->id != $target_form_id) return $confirmation; $user_id = get_current_user_id(); if (!$user_id) { return __('请先登录后再提交表单', 'text-domain'); } $profile_post_id = get_user_profile_post_id($user_id); $post_args = []; if ($profile_post_id) { // 更新已有Profile文章 $post_args['ID'] = $profile_post_id; wp_update_post($post_args); } else { // 创建新的Profile文章 $user_data = get_userdata($user_id); $post_args = [ 'post_type' => 'profile', 'post_title' => $user_data->display_name . ' 的个人资料', 'post_status' => 'publish', 'post_author' => $user_id ]; $profile_post_id = wp_insert_post($post_args); } // 同步表单数据到ACF字段 foreach ($formData as $field_name => $value) { // 跳过Fluent Form内置的系统字段 if (str_starts_with($field_name, '_')) continue; // 仅更新存在的ACF字段 if (get_field_object($field_name, $profile_post_id)) { update_field($field_name, $value, $profile_post_id); } } return $confirmation; }
4. 额外优化:移除无用的表单字段
如果之前添加了Fluent Form自带的「Post/CPT创建」字段,可通过以下代码移除(避免干扰用户操作):
add_filter('fluentform/form_fields', 'remove_cpt_field_from_profile_form', 10, 2); function remove_cpt_field_from_profile_form($fields, $formId) { $target_form_id = 123; // 替换为你的目标表单ID if ($formId != $target_form_id) return $fields; foreach ($fields as $key => $field) { if ($field['type'] == 'post_cpt') { unset($fields[$key]); } } return $fields; }
内容的提问来源于stack exchange,提问作者funkyfreaka
相关产品推荐
相关产品推荐

