So I have this contact form widget which can be placed anywhere, in sidebar or as a shortcode – basically you can have multiple contact forms on a page. They both submit form content to the php file located in the theme folder and all that works fine.
Each widget has 2 options:
- page id when email is sent successfully, and - page id when there has been an error.
I want form processing php file to load wp environment, send email, pick the permalinks for pages and redirect accordingly: to success page or error page.
All this works fine, email is sent, etc. But: there is a problem with the redirects. I’ve tried all of those and none is working:
- header(‘Location: ’ . $location); - wp_redirect( $location ); exit; - wp_safe_redirect( $location ); exit; - tried also to use ob_start(); and ob_end_clean(); to make sure headers are not sent
Does anyone know what’s the problem?
Thanks
- Author had a File in an Envato Bundle
- Author was Featured
- Bought between 1 and 9 items
- Europe
- Exclusive Author
- Has been a member for 2-3 years
- Item was Featured
- Referred between 100 and 199 users
Just a guess, i did not work with wp_redirect. This is what they say:
Please note: wp_redirect will not be called if the page has started, so make sure to call it higher up.
And the question is: does your widget area ( sidebar ) come before the main page loop? If not, move it there. This is just a guess, i never worked with it to be sure.
The form processing php file has no layout:
1) loads wp environment 2) sends email 3) based on result it should redirect
I am using wp_mail function, not the php native one. This is the only reason to include wp-load.php. I might try this without it…
Well, what I would do here is I wouldn’t manually load WP environment as it is not the best practice when building themes.
The most convenient method is to hook into some WordPress action that runs very early (template_redirect would be a good pick here) and run your function. Now make sure your forms sends some ‘action’ variable, like ‘send_email’. Your function should check if the action attribute is set to ‘send_email’ and proceed from there.
Grab all the form data, send email, then grab the post/page ID and do wp_redirect() from there. Also remember to do a nonce check for basic security. 
I created a class which processes the form. If post value exist, it makes a new instance and does its thing.
Anyway, thanks pogoking!
