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

Read More

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.

Related posts

Leave a Reply

2 comments

  1. 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.

  2. Moving get_header(); to the bottom of that code should fix the problem. Your code will execute before any headers are sent and the redirect will work.

    // ...
    wp_redirect( get_permalink($pid) );
    exit();
    //insert taxonomies
    } 
    get_header(); ?>
    

    I assume there is more code on the page below what you posted? If not I don’t see the need for get_header() at all.

    The only benefit I can see to using a hook as Milo suggests is that you might be able to avoid some overhead if you pick an early enough hook. You could shave a fraction of a second off of processing.