Mekong
Mekong

Reputation: 449

Cannot get wp_redirect to work

I'm trying to send an email using wp_mail and then, if mail is sent successfully, redirect user to another page (or, if not successful, to an error page).

My code is shown below. The email is actually sent, so wp_mail is working, but I cannot get the redirect to work.

<?php

/*  Template Name: Redirect Template */

?>

<?php

$to = "[email protected]";

$subject = 'This is a test.';
$message = 'This is a test of the wp_mail function.';
$headers = '';

$sent_message = wp_mail( $to, $subject, $message, $headers);

if ($sent_message) {

    $url_1 = "http://www.some-url.com";
    wp_redirect($url_1);
    exit();

} else {
    $url_2 = "http://www.some-other_url.com";
    wp_redirect($url_2);
    exit();
}

?>

<?php get_header(); ?>


        <?php while ( have_posts() ) : the_post(); ?>

            <?php get_template_part( 'content', 'page' ); ?>

        <?php endwhile; // end of the loop. ?>


<?php get_footer(); ?>

Upvotes: 0

Views: 602

Answers (1)

rnevius
rnevius

Reputation: 27112

You need to get rid of the white space between your closing and opening PHP tags. Because you have this space, WordPress is initiating output before the redirect runs (which isn't allowed). Get rid of the following at the top of your file:

?>

<?php

so that the top of the file becomes:

<?php

/*  Template Name: Redirect Template */

$to = "[email protected]";

Upvotes: 2

Related Questions