- Creating a custom URL that can me use as API. At first we need to use init hook in function.php
/* allow ajax request api for custom url*/
add_action('init', function(){
add_rewrite_tag('%moms_type%', '([0-9]+)');
add_rewrite_rule('ajax-api/momstype/([0-9]+)/?', 'index.php?moms_type=$matches[1]', 'top');
});
2. Use template_redirect hook for return response
/* Get Ajax request for changing cookies and set cookies */
add_action('template_redirect', function() {
global $wp_query;
$momsTypeId = $wp_query->get('moms_type');
$momsType = ($momsTypeId == 1) ? "business" : "private";
if(!empty($momsTypeId)){
setrawcookie('momsType', rawurlencode($momsType), time()+62208000, '/', $_SERVER['HTTP_HOST']);
wp_send_json_success([
'cookiesphp' => $_COOKIE["momsType"],
]);
exit;
}
});
3. Ajax call function from jquery script
const requestSetCache = async (type) => {
try {
const response = await fetch("https://www.test.cirk-l.pl/ajax-api/momstype/"+type+"/");
const data = await response.json();
console.log({data});
location.reload();
}catch(err) {
console.log(err);
}
}
4. Add click event to execute the Ajax request
$("#momsType-footer").change(function (event) {
if($(this).val() == "business"){
requestSetCache(1);
}else{
requestSetCache(2);
}
});