Help with use of wp_redirect in custom plugin
-
I’m struggling with (the infamous) ‘headers already sent’ error when attempting to use wp_redirect (actually wp_safe_redirect) within a plugin that I am creating from scratch.
My use case is fairly straightforward. I am building a small application accessible from the main website that employees will be accessing to view information about their performance. Since the employees don’t have website WP logins, i am providing a simple login facility with a single login page which (a) validates the user and (b) depending on the type of role they have in the application, redirects them to one of up to three views (pages). A database table stores the username/password/role combination. Once validated, the user is to be offered the choice of entering one of a few pages to look up their information. My problem is here, in the (re)direction of the user to any of these choices.
As i said, i’m doing this in a plugin instantiated by a shortcode on a page and i’ve initially created it as an object-oriented class and in the class constructor, i’ve got the following code:
add_action('init', array($this, 'redirect_to_funnel')); function redirect_to_funnel() { $slug = get_post_field( 'post_name', get_post() ); if ($slug == 'login-page' && $_SESSION['login_attempted']) { wp_safe_redirect(home_url('my-options-choice-page')); exit(); } }
This generates the dreaded ‘headers already sent’ error. I’ve tried numerous things. I’ve tried different hooks (‘init’, ‘wp_loaded’, ‘template_redirect’). I have read suggestions of putting this code into the theme’s functions.php file, which i have also tried with no success. I’ve also tried redirecting to my options page via the login form’s ‘action’ like this:
function render_login_form() { <h1>Commission Tracker Login</h1> <div class="login-panel"> <form action="option-routing.php" method="POST"> <input type="hidden" name="action" value="custom_login_redirect"> <label for="userid">User ID:</label> <input type="text" id="userid" name="userid" placeholder="(Your UserID)" required></br> <span><?php if (isset($userid_error)) echo {$userid_error}; ?></span> <label for="pwd">Password:</label> <input type="text" id="pwd" name="pwd" placeholder="(Your Password)" required></br> <span><?php if (isset($password_error)) echo $password_error; ?> </span> <span><?php if (isset($invalid_login_error)) echo $invalid_login_error; ?> </span> <input type="submit" value="Submit" name="example_form_submit"> </div> </div>'; return $login_form; }
Same result. I’m baffled on how to do this within a plugin. Can anyone suggest a solution? Am i tying this to the wrong hook? Is my code in the wrong place? This error is baffling me to no end. Can someone help me to understand this and help me out of this maze?
- You must be logged in to reply to this topic.