I know it’s not the best way, but made it work like this:
JS
document.querySelector('.age-gate__submit--yes').addEventListener('click', async (e) => {
const header = {
'accept': 'application/json',
'content-type': 'application/json',
'Access-Control-Allow-Origin': '*'
};
const email = document.getElementsByClassName("age-email-input")[0].value;
const endpointUrl = https://yoursite.com/wp-json/yoursite/age-gate-email;
const rawResponse = fetch(endpointUrl, {
method: 'POST',
headers: header,
body: JSON.stringify({email: email })
});
});
Theme Function.php
function ageGateAddUser( WP_REST_Request $request ) {
$parameters = $request->get_json_params();
$email = $parameters['email'];
if($email!=""){
//Do whatever you need here
}
return new WP_REST_Response($email);
}
add_action( 'rest_api_init', function () {
register_rest_route( 'yoursite', 'age-gate-email', array(
'methods' => 'POST',
'callback' => 'ageGateAddUser',
));
});