3

how to prevent/block direct access to a thank you page, only access if redirected from submiiting a form (in a different page)?

2
  • Is the page with the form the same or is the form implemented on many/all pages? – kero Jan 5 '18 at 12:23
  • the form is implemented in one page only , it's cf7 form so the redirection works well, what I still need is to block direct access. – turcospeed Jan 5 '18 at 12:46
4

If the form is redirecting from one page only, you can easily use wp_get_referer() to check for it and if not, redirect.

add_action('template_redirect', function() {
    // ID of the thank you page
    if (!is_page(12345)) {
        return;
    }

    // coming from the form, so all is fine
    if (wp_get_referer() === 'URL_OF_FORM') {
        return;
    }

    // we are on thank you page
    // visitor is not coming from form
    // so redirect to home
    wp_redirect(get_home_url());
    exit;
} );
9
  • 1
    Shouldn't there be a die/exit after redirect? – Krzysiek Dróżdż Jun 9 '18 at 20:14
  • 1
    @KrzysiekDróżdż good catch, added it – kero Jun 9 '18 at 22:51
  • @kero, I have one doubt what URL I have to use it in URL_OF_FORM? I added your code and I have a form on the contact us page – user9437856 Nov 3 '20 at 7:28
  • 1
    I tried like this if (wp_get_referer() === get_site_url().'/contact-us/') and it's working – user9437856 Nov 3 '20 at 12:14
  • 1
    upvote from my side – user9437856 Nov 3 '20 at 18:57
1

Don't know why the above code don't work for me. However the below code worked perfectly.

<?php
    function thank_you_rd(){
        if ( ! is_page('thank-you')) {
            return;
        }
        if (wp_get_referer() == '/contact-us/') {
            return;
        }
        wp_redirect( get_home_url() );
    }
    add_action('template_redirect', 'thank_you_rd');
?>

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