wp_redirect not working after submitting form

I’m using this redirect after inserting a post. It’s not working, it only refreshes the page the form is on. I know the $pid is getting the post ID so what is the problem? This is the very end of my php code for handling the form submission.

$pid = wp_insert_post($new_post);

update_post_meta($pid,'domain',$domain);
update_post_meta($pid,'keywords',$keywords);

wp_redirect( get_permalink($pid) );
exit();

Here is a pastebin of the complete code

Using Better HTTP Redirects it’s output is, and it links the word here to the correct newly published post.

302 Found
The document has moved here.

2 s
2

You can only use wp_redirect before content is sent to the browser. If you were to enable php debugging you’d see a “headers already sent” error due to get_header() on the first line.

Rather than process the form in the template, you can hook an earlier action, like wp_loaded, and save some queries to the db if you’re just going to redirect away.

EDIT, example-

add_action( 'wp_loaded', 'wpa76991_process_form' );
function wpa76991_process_form(){
    if( isset( $_POST['my_form_widget'] ) ):
        // process form, and then
        wp_redirect( get_permalink( $pid ) );
        exit();
    endif;
}

Using an action, you can keep the code out of and separated from your templates. Combine this with a shortcode to output the form and wrap it all in a class to save state between processing/output, and you could do it all without touching the front end templates.

Leave a Comment