0

I'm trying to register a custom route to validate a groupon voucher code for a landing page. I registered the route in functions.php like so:

    // Adding Custom Voucher Route 

add_action('rest_api_init','register_voucher_endpoint');

function register_voucher_endpoint() {
    register_rest_route(
        'voucher',
        'verify/(?<voucher_code>)',
        array(
            'methods'=> 'POST',
            'callback'=>'verify_voucher'
        ));
}


function verify_voucher($request) {
    return $request['voucher_code']; 
}

I set the link on the form action like this

<form action="/voucher/verify" method="POST">
                            <h5 class="title">Please enter your 8-character Groupon Voucher Code to redeem your
                                purchase</h5>
                            <p>Note: You will have a voucher code for each product you buy on Groupon. For example,
                                if you bought 2 CBD sprays on Groupon, you'll have to enter 2 voucher codes, one
                                for each spray.</p> 
                                <input required="" class="branded-input margin-bottom" type="text"
                                minlength="8" maxlength="8" title="voucher-code" name="voucher-code" placeholder="Enter your 8 Character Groupon code">
                            <input type="submit" value="Redeem My CBD!" class="btn btn-color-primary btn-style-bordered btn-size-large">

When I click the submit button or go to the registered route manually, it redirects to the home page and the network tab shows that the 'verify' route returned a 301. The site is using redirection but none of the options include the custom route I registered.

Two main questions:

  1. Why is this redirect happening?
  2. How do I capture the code entered into the input field in the callback function?

Thanks in advance for your answer.

0

Just a guess: Your regular expression 'verify/(?<voucher_code>)' is not correct. Have a look here. They are using e.g. (?P[a-zA-Z0-9-]+) there's a P inside. Another reason could be that you are missing a / before the verify. Try this:


function register_voucher_endpoint() {
    register_rest_route(
        'voucher',
        '/verify/(?P<voucher_code>[a-zA-Z0-9-]+)',
        array(
            'methods'=> 'POST',
            'callback'=>'verify_voucher'
        ));
}

[a-zA-Z0-9-] defines the regular expression group for this endpoint.

To answer question nr. 2: check the global $_POST array. There you should have an voucher-code entry which you can access with $_POST['voucher-code']. I'm not 100% sure my answer is correct.

  • Thanks for the answer - although this didn't work, it's still redirecting :/ – Adam French Jan 19 at 0:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.