请求实现添加/编辑Term时分配Post的PHP代码(ACF save_post)
实现Term编辑时分配文章的方案
首先你需要先在ACF中创建一个字段组,关联到你目标的分类法(比如分类、标签或自定义分类法)的Term编辑页面,字段类型选择「文章」(支持多选),字段名设为assigned_posts(可自定义,代码里对应即可)。
接下来将以下代码添加到主题的functions.php文件或自定义插件中:
/** * 保存Term时将选中的文章分配到该Term */ add_action('save_term', 'assign_posts_to_on_term_save', 10, 3); function assign_posts_to_on_term_save($term_id, $tt_id, $taxonomy) { // 检查权限 if (!current_user_can('edit_term', $term_id)) { return; } // 检查ACF字段是否存在 $assigned_posts = get_field('assigned_posts', 'term_' . $term_id); if (!$assigned_posts) { return; } // 处理多选情况(ACF返回数组,单选返回单个ID) $post_ids = is_array($assigned_posts) ? $assigned_posts : array($assigned_posts); // 遍历文章ID,分配当前Term foreach ($post_ids as $post_id) { // 检查文章是否存在 if (!get_post($post_id)) { continue; } // 将Term分配给文章,第三个参数false表示追加,true表示替换现有分类 wp_set_object_terms($post_id, $term_id, $taxonomy, false); } // 可选:移除未选中文章的该Term关联 // 获取该分类法下所有已关联此Term的文章 $existing_posts = get_objects_in_term($term_id, $taxonomy); if ($existing_posts) { $posts_to_remove = array_diff($existing_posts, $post_ids); foreach ($posts_to_remove as $post_id) { wp_remove_object_terms($post_id, $term_id, $taxonomy); } } }
代码说明:
- 使用
save_term钩子监听Term的保存事件(比save_post更适配Term操作场景) - 先验证用户权限,确保操作合法
- 获取ACF字段中选中的文章ID列表
- 遍历文章ID,用
wp_set_object_terms将Term分配给对应文章 - 可选的移除逻辑:如果用户取消了某些文章的选择,会自动从这些文章中移除当前Term的关联
内容的提问来源于stack exchange,提问作者mhfoster
相关产品推荐
相关产品推荐

