So the reason you are getting this error is because the response headers are already sent and you cannot update headers after the response. To redirect earlier you have two options:
- You can use the
wp_redirect()
function and do your redirect at runtime before the page renders.
You can hook into the template redirect action and do your wp_redirect()
there.
function my_redirect() {
exit( wp_redirect( 'url' ) );
}
add_action( 'template_redirect', 'my_redirect' );
Both methods hook into Wordpress' own redirect architecture. If you have issues with these methods, you may want to consider refactoring your code so that your redirect conditions are set up earlier in the stack.
For full disclosure, if you absolutely need to redirect after headers have been sent, you can always use a Javascript redirect after the page loads. You can simply add this to your php file (though I would recommend refactoring instead of this method):
function append_script() {
echo '<script type="text/javascript">window.location.replace("url");</script>';
}
add_action('wp_head', 'append_script');
Again, I would suggest going a different route than this, but it will get the job done. You would want to place this code within your conditional for the redirect, not in the document scope of the functions file.
UPDATE:
After rereading your question a couple more times, it seems like you might be putting the PHP header function within the document on the button you are trying to make redirect. If that is the case, you should definitely not be using the header()
function. This function specifically updates header information before the page renders. If the user is clicking a link, the page has already rendered and the response has already been parsed.
What you are trying to do is an event-based redirect. You either need to parse the URL you need and add it to an <a>
tag or setup an onclick
attribute for your button with the same URL:
<button onclick="window.location.replace('url')">Button Text</button>
The only way that I could see you using PHP on an event-based redirect (ie the button click) is if you sent the user to a handler to parse the request and send the user to the appropriate URL. Otherwise, you are stuck with the methods listed above.