phpwordpress

Redirects to the “Thank you” page depending on the selected language in WordPress


I'm using code that redirects to a “Thank You” page after sending a message from Contact Form 7. This code is located in the child theme's functions.php file.

add_action( 'wp_footer', 'mycustom_wp_footer' );
function mycustom_wp_footer() {
?>
    <script>
        document.addEventListener( 'wpcf7mailsent', function( event ) {
            location = "//site.com/thank-you/";
        }, false );
    </script>
<?php
}

This code works, except that there is a Polylang plugin on the site. That's why I have the “Thank you” page in several languages.

If I switch to Arabic or Chinese, it still redirects to the //site.com/thank-you/ page by default.

How can I fix this and make the redirect to the “Thank You” page depending on the selected language?


Solution

  • I don't know much about "Polylang" plugin but upon searching "pll_get_post" might do it.

    replace your code with this code and "1" with your thank you page post id.

    add_action( 'wp_footer', 'mycustom_wp_footer' );
    function mycustom_wp_footer() {
        if ( function_exists( 'pll_get_post' ) ) {
            // Get the translated Thank You page URL
    
            $page_id = 1; // Replace with the actual Thank You page ID in default language
            $new_thank_you_url = get_permalink( pll_get_post( $page_id ) );
        }
        ?>
        <script>
            document.addEventListener( 'wpcf7mailsent', function( event ) {
                location = "<?php echo esc_url( $new_thank_you_url ); ?>";
            }, false );
        </script>
        <?php
    }
    

    Here is the link if you want to study about the function

    https://polylang.wordpress.com/documentation/documentation-for-developers/functions-reference/