您可以将代码包装在函数中,然后使用按钮激活它。创建一个按钮并为其onclick
事件:
<span onlclick="javaSubscribe();">Subscribe</span>
现在,单击按钮后向服务器发出AJAX请求:
function javaSubscribe() {
// We need the ID for user and tag. Let\'s retrieve it from a div we will create later
var id = getElementById(\'user-id-div\').textContent;
var tag = getElementById(\'tag-id-div\').textContent;
// Time for the real fun, let the call to the function begin
jQuery.ajax({
type: \'GET\',
url: \'http://example.com/wp-json/some_path_here/v1/my_subscribe?user_id=\' + id + \'&tag_id=\' + tag,
data: { get_param: \'value\' },
dataType: \'json\',
success: function (data) {
if (data != null) {
// Do whatever you want with the response
}
}
});
};
然后注册REST路由,并将代码包装到其回调函数中:
add_action( \'rest_api_init\', function () {
//Path to ajax function
register_rest_route( \'some_path_here/v1\', \'/my_subscribe/\', array(
\'methods\' => \'GET\',
\'callback\' => \'subscribe_php\'
) );
});
// The function we set in the callback
function subscribe_php(){
// Retrieving the data from our AJAX request
if (isset($_GET[\'user_id\'])) {
$user_id = $_GET[\'user_id\'];
}
if (isset($_GET[\'tag_id\'])) {
$tag_id = $_GET[\'tag_id\'];
}
$currentList = $current_user->subList;
$tagStr = " " . $tag_id . ",";
$update;
if(strpos($currentList,$tagStr)!== false) {
return \'Already in list\';
}
else {
$update = $currentList . $tagStr;
update_user_meta($user_id,\'subList\',$update);
return \'Added to list\';
}
}
但是您需要有人将数据传递给函数。我建议您在一个隐藏的div中输出它,然后在PHP函数中检索它。您可以在模板中使用此选项,例如:
<div id="user-id-div"><?php echo wp_get_current_user()->ID; ?></div>
<div id="tag-id-div"><?php echo get_query_var(\'tag_id\'); ?></div>
使用此方法输出所有需要的信息并将其传递给函数。