如何将JavaScript变量传入PHP函数实现ACF字段更新
实现方案
你无法直接在前端JavaScript中调用服务端运行的PHP函数,需要通过WordPress原生AJAX接口完成前后端数据传递,最终调用ACF函数完成字段更新,具体实现步骤如下:
1. 后端PHP代码配置
将原有PHP代码替换为以下内容,完成脚本加载、AJAX接口注册、安全校验与字段更新逻辑:
<?php // 挂载脚本到wp_enqueue_scripts钩子 add_action('wp_enqueue_scripts', function(){ wp_register_script( 'custom-acf-js', get_template_directory_uri() . '/library/scripts/script-js.js', ['jquery', 'acf-input'], '1.0.0', true); // 向前端传递AJAX地址与安全校验凭证 wp_localize_script('custom-acf-js', 'acfCustom', [ 'ajax_url' => admin_url('admin-ajax.php'), 'nonce' => wp_create_nonce('acf_update_verify') ]); wp_enqueue_script('custom-acf-js'); }); // 注册登录用户可调用的AJAX接口 add_action('wp_ajax_update_bewerber_field', 'acf_update_bewerber_handler'); function acf_update_bewerber_handler(){ // 安全校验 if(!check_ajax_referer('acf_update_verify', 'nonce', false)){ wp_send_json_error('校验失败', 403); exit; } // 参数校验 if(empty($_POST['post_id']) || !isset($_POST['selected_val'])){ wp_send_json_error('参数不全', 400); exit; } // 权限校验:判断当前用户是否有编辑该文章的权限 $post_id = intval($_POST['post_id']); if(!current_user_can('edit_post', $post_id)){ wp_send_json_error('无操作权限', 403); exit; } // 消毒传入值 $field_val = sanitize_text_field($_POST['selected_val']); // 更新ACF字段 $update_res = update_field('bewerber_einstufen', $field_val, $post_id); if($update_res){ wp_send_json_success('更新完成'); }else{ wp_send_json_error('更新失败', 500); } exit; } ?>
2. 前端JavaScript逻辑调整
将原有JS代码替换为以下内容,下拉选择变更时向后端接口传递选中值与对应文章ID:
jQuery(document).on('ninja_table_loaded', function (event, $table, settings) { const selectList = document.querySelectorAll('select'); selectList.forEach(selectEl => { selectEl.addEventListener('change', function(){ // 获取当前选中值 const currentVal = this.value; // 获取对应文章ID,优先取最近的tr行,去除内容前后的空白字符避免ID识别错误 const rowParent = this.closest('tr') || this.parentElement.parentElement; const postId = rowParent.querySelector("p").textContent.trim(); // 发送AJAX请求 jQuery.post(acfCustom.ajax_url, { action: 'update_bewerber_field', nonce: acfCustom.nonce, post_id: postId, selected_val: currentVal }, function(resp){ console.log(resp.success ? '字段更新成功' : '字段更新失败', resp); }).catch(err => console.error('请求异常', err)); }) }) });
注意事项
- 请确认前端获取
postId的逻辑是否正确:如果存储ID的p标签内包含其他HTML内容或冗余文本,需要调整选择器规则,确保拿到纯数字格式的文章ID - 非文本类型的ACF字段(如多选、关系字段)需要调整PHP端的值消毒逻辑,匹配字段存储格式要求
- 不要省略nonce校验与权限判断逻辑,避免接口被恶意调用篡改数据
内容的提问来源于stack exchange,提问作者Gatti
相关产品推荐
相关产品推荐

