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