使用 AJAX 更新自定义 Wordpress 字段



我正在尝试使用Ajax更新Wordpress中的自定义字段(例如,通过单击按钮将表单文本输入替换自定义字段文本(。 我正在使用高级自定义字段插件并按照我在这里找到的示例进行操作,但这似乎不起作用: https://support.advancedcustomfields.com/forums/topic/use-update_field-with-ajax/

我所做的是:

(1(将html表单添加到我的单(后类型(中.php

<form id="test-form" action="">
<input type="text" name="input-test" value="<?php the_field('field-name'); ?>">
<input type="submit" value="Update">
</form>

(2( 函数中的update_field函数.php(这是一个 ACF 函数(

function test_function() {
$input_test = $_POST['input-test'];
if (!isset($input_test) || $input_test == "") { $input_test = "Fall Back"; }
update_field('field-name', $input_test);
wp_die();
}
add_action( 'wp_ajax_nopriv_test_function',  'test_function' );
add_action( 'wp_ajax_test_function','test_function' );

(3( 在函数中排队 Js 脚本.php

function theme_scripts() {
wp_enqueue_script( 'functionality', get_template_directory_uri() . '/js/functionality.js', array ( 'jquery' ), 1.1, true);
wp_localize_script('functionality', 'MyAjax',
array(
'ajaxurl' => admin_url('admin-ajax.php'),
'postCommentNonce' => wp_create_nonce('myajax-post-comment-nonce')
)
);
}
add_action( 'wp_enqueue_scripts', 'theme_scripts' );

(3(创建Javascript文件js/function.js

jQuery(document).ready(function() {
var ajaxurl = 'http://'+window.location.host+'/wp-admin/admin-ajax.php';
var form = "#test-form";
jQuery(form).submit(function(event) {
event.preventDefault();
jQuery.ajax({
url: ajaxurl + "?action=test_function",
type: 'post',
data: jQuery(form).serialize(),
success: function(data) {
console.log("SUCCESS!");
},
error: function(data) {
console.log("FAILURE");
}
});
});
});

不知道我错过了什么,因为我对 Ajax 很陌生。我只是得到"成功",但该字段没有得到更新。我还尝试了此处显示的变体 https://www.youtube.com/watch?v=Z0Jw226QKAM 结果相同。

只需将您的success回调更新为如下所示,它就会起作用:

...
success: function(data) {
console.log("SUCCESS!");
$('name="input-test"').val(data)
},
...

最新更新