Skip to content
Read For Learn
Read For Learn
  • Database
    • Oracle
    • SQL
  • C
  • C++
  • Java
  • Java Script
  • jQuery
  • PHP
Read For Learn
  • Database
    • Oracle
    • SQL
  • C
  • C++
  • Java
  • Java Script
  • jQuery
  • PHP

Proper way to pass credentials in a custom login form to avoid “headers already sent”

Upon successful login wp_signon() sets a cookie in the http response header. Hence it has to be called before any HTML output is sent to the browser. Otherwise the “headers already sent” error will occur.

After a successfull login you should redirect your user. Otherwise the login information will not present when the page HTML is rendered.

A very sketchy but working code:

// process login requests each time wordpress renders a page. 
function my_custom_login_process() {
    // check if login credentials are present in the current http request
    if ( isset( $_POST['user_login'] ) && isset( $_POST['user_password'] ) ) {
        // try login
        $user = wp_signon( $_POST );

        if ( is_wp_error($user) ) // didn't work. Tell the user.
            exit('Nope...');
        else // worked! Get him somewhere.
            wp_redirect( get_bloginfo('url') );
    }
}
add_action('after_setup_theme','my_custom_login_process');

Additionally you should protect your login form with a nonce, and add a nonce verification to the function above. The easiest way to do this is by using wp_nonce_field() in the login form.

Nonces explained

[EDIT]: A Nonce is a unique token, that gets registered along with a form. It is mainly used to make sure that a form has been generated by the Webserver, before any data is accepted for further processing. All forms in the admin area are using nonces (or at least should do).

During the login process it will provide basic protection against brute force attacks. (This means flooding your WordPress with blank POST requests containing arbitrary username / password combinations.)


(BTW: It seems like you have a little misconception on hooks. You really should not register (do_action()) and call a hook (do_action()) with arbitrary function arguments. Other plugins might also have registered their functions. This article looks like a pretty good starting point for a deeper understanding.)

Related Posts:

  1. Need Help Determining Where Header Error is Happening
  2. WordPress Plugin Development – Headers Already Sent Message
  3. No Error Log File, no debug info
  4. How should one implement add_settings_error on custom menu pages?
  5. Can someone explain what wp_session_tokens are, and what are they used for?
  6. Prevent notice and warnings in error_reporting?
  7. Init action hook running late after PayPal’s return url?
  8. Clarity needed on usage of multiple 403 forbidden header() functions at the beginning of the plugin files
  9. How to log plugin errors to plugin error_log file
  10. How to check WordPress website username and password is correct
  11. Log in from one wordpress website to another wordpress website
  12. How to get Login Error messages on a custom template
  13. Catch own Exceptions
  14. Problems after wp_set_password() containing an apostrophe
  15. Headers already sent error with CSV export plugin
  16. Get file headers in custom file
  17. Throw 403 in a plugin [duplicate]
  18. Using ob_start() in plugin
  19. Adding custom code into header.php using a plugin
  20. why don’t I get error messages in admin when developing?
  21. WP_Error handles errors, but how can I show success with a message?
  22. Two-step login process – Is it possible?
  23. How can I change HTTP headers only to posts of a specific category from a plugin
  24. Settings API – Undefined Index when unchecking checkbox
  25. The plugin generated 80 characters of unexpected output!
  26. Warning: Cannot modify header information – headers already sent
  27. How do I approach removing menu items on the fly based on settings in my plugin?
  28. Error : “Updating failed: The response is not a valid JSON response” with custom shortcode
  29. Cannot modify header information – headers already sent by pluggable.php
  30. How can I display an error message after post has been saved?
  31. Execution limit and Memory limit errors even i changed to 1024M and 600(cache.php,load.php)?
  32. Header Button Chance Polylang Elementor
  33. Is there any way to check for user login and send him to login?
  34. An echo line in a transition_post_status action leads to “cannot modify header information – headers already sent by”
  35. Two functions utilizing registration_errors filter
  36. How can I gracefully escape an error condition?
  37. External Authentication, session_tokens not destroyed on logout
  38. Verify if user is wordpress logged in from another app since wordpress 4.0
  39. How to customize login process
  40. wp_insert_user() function password never match
  41. Does wp_login only trigger before an user signs in into the admin panel?
  42. Logout users upon login, based on caps/role?
  43. Serve text/html from wp-json API via WPEngine, headers not being set properly
  44. Is it possible to make sure that only my plugins output is shown to the enduser?
  45. Password field is empty when using wp_signon();
  46. Plugin Development for registered users
  47. How to give a download link to a .csv file from the custom plugin?
  48. Enqueue script globally
  49. WP Multisite login not working on one subsite. Possibly cookies/ history issue?
  50. WordPress debug messages not displaying
  51. Custom Login Page — wp_signon Headers Already Sent?
  52. Adding custom stylesheet into header.php using a plugin
  53. How do I validate extra pin field on my WordPress login form page?
  54. Custom Post Type Object – Undefined Variables
  55. How to redirect home page to another page after login for all user?
  56. Reporting errors in a shortcode plugin
  57. What might be the reason of Couldn’t fetch mysqli_result on another domain?
  58. Plugin can’t be activated [closed]
  59. How do I debug an error that a plugin is causing?
  60. How to share user data across multiple WordPress websites?
  61. “Rendering of admin template [path to template] failed”
  62. Is there any way to pass messages from a script to a redirect target in a hidden fashion?
  63. Why does website stretch and white space on load? [duplicate]
  64. Downloading File via headers doesnt work
  65. Import images remotly run through timeout error
  66. Error code when migrate
  67. WordPress Favicon not Working For Images/Videos/PDFs
  68. WPGut – Updating failed and shortcode?
  69. GET request return value as error instead of success
  70. Allowing duplicating users with same user_login and user_email
  71. How to Login a User inside a Plugin and Redirect to page?
  72. Using custom IDP with WP
  73. Hiding the WordPress login and password fields from login page
  74. WP_Fatal_Error_Handler OR WP_Error OR try/catch
  75. Custom Plugin activation error in Multisite
  76. Two same AJAX calls – one is working, other doesn’t
  77. redirect_to how to make it simply work with get parameter or similar?
  78. Some data has already been output, can’t send PDF file – fpdf issue in WordPress
  79. Warning: Illegal string offset – on homepage
  80. Headers already sent on custom plugin (Export function)
  81. How to force download a plugin generated file?
  82. Not able to Update database while creating a custom module
  83. Plugin error on activation – breaks page encoding and prints the code of plugin php files
  84. Multiple Users Logged In Causing Incorrect Account Returned
  85. Getting error of unexpected output during activation
  86. Get user logged in status from within a plugin. $current_user not defined
  87. Need edit profile link in the menu for logged in users
  88. Create a Custom Login System in WordPress [closed]
  89. how can I insert a link on login page
  90. Trying to build a plugin – Cannot modify header information
  91. user can login from single account detail from multiple locations(computer) at the same time [closed]
  92. Why is there a bunch of WordPress HTML code in my browser CSV download?
  93. how to works woocommerce cart hash
  94. Hello dolly type plugin that allows people to add their own
  95. Is the usage of ON DELETE CASCADE wrong or not allowed on wordpress?
  96. Reset plugins version cache | pre_set_site_transient_update_plugins
  97. TinyMCE editor turns white on Biographical info [closed]
  98. How I can use order by of the custom post title?
  99. Nothing happens on WordPress Update command
  100. Ajax Contact form plugin [closed]
Categories plugin-development Tags errors, headers, login, plugin-development
Can’t show custom post thumbnail sizes as background images
How To Remove Certain category Posts From the Blog Page

Recommended Hostings

Cloudways: Realize Your Website's Potential With Flexible & Affordable Hosting. 24/7/365 Support, Managed Security, Automated Backups, and 24/7 Real-time Monitoring.

FastComet: Fast SSD Hosting, Free Migration, Hack-Free Security, 24/7 Super Fast Support, 45 Day Money Back Guarantee.

Recent Added Topics

  • Bug in translation system: load_theme_textdomain() returns true, files are available and accessible but the language defaults to english
  • Custom Elementor controls not appearing in the widget Advanced tab using injection hooks
  • Get the name of the template/*html file used
  • Trying to Add Paging to Single Post Page
  • Sharing media files between live and staging servers
  • How to display the description of a custom post type in the dashboard?
  • Critical error on image display
  • Copying WP data and files into new install?
  • How to determine the DirectAdmin WordPress backup date?
  • How to get list of ALL tables in the database?
© 2026 Read For Learn
  • Database
    • Oracle
    • SQL
  • algorithm
  • asp.net
  • assembly
  • binary
  • c#
  • Git
  • hex
  • HTML
  • iOS
  • language angnostic
  • math
  • matlab
  • Tips & Trick
  • Tools
  • windows
  • C
  • C++
  • Java
  • javascript
  • Python
  • R
  • Java Script
  • jQuery
  • PHP
  • WordPress