prevent/block direct access to a thank you page

The question:

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

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

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)) {

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

    // we are on thank you page
    // visitor is not coming from form
    // so redirect to home
} );

Method 2

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

    function thank_you_rd(){
        if ( ! is_page('thank-you')) {
        if (wp_get_referer() == '/contact-us/') {
        wp_redirect( get_home_url() );
    add_action('template_redirect', 'thank_you_rd');

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment