我很久没有这样做了,所以这可能并不完美,但这里是我关于使用 AJAX(在 jQuery - 一个 JavaScript 库中)解决问题的想法的要点。
Ajax 将允许您使用钩子将 JSON 字符串发送到 functions.php 中的 php 函数。
首先在你的functions.php中你需要本地化wp ajax脚本。
function add_ajax(){
wp_localize_script( 'main-script', 'options', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ));
}
add_action( 'wp_head', 'add_ajax');
然后你需要添加一个动作钩子,它以wp_ajax_开头。这个钩子绑定到一个函数,该函数将处理您的选项并将在 jQuery 脚本中调用。
add_action( 'wp_ajax_options', 'handle_options' );
add_action( 'wp_ajax_nopriv_options', 'handle_options' );
function handle_options() {
$options = $_POST['options'];
//DO SOMETHING
wp_die(); // this is required to terminate immediately and return a proper response
}
之后,您需要在用户选择他们的选项后进行 ajax 调用,这会将您的数组转换为 JSON 并使用操作挂钩 wp_ajax_options 发送。像这样的:
var options = = JSON.stringify(yourArray);
jQuery.ajax({
type: 'POST',
url: output.ajax_url,
data : {
action : 'options',
'options': options
},
success: function(response){
//you can do something here with the response.
}
});
一定要查看这些资源以获取更多信息:
https://codex.wordpress.org/AJAX_in_Plugins
https://premium.wpmudev.org/blog/using-ajax-with-wordpress/