How to WordPress Login User Programmatically in Custom PHP Script

WordPress is the most popular CMS among all others due to the opensource community and regular updates. Even more, WordPress provides more flexibility than any other blogging platform.

There are lots of free and paid WordPress themes available for blogging and websites. Besides, developers love to use these elegant and exotic themes. But custom scripts may not be compatible with WordPress.

However, there is a solution to log in the user to the custom script direct via WordPress.

Read Also: Create new Widget in WordPress

Custom PHP Script Log in Using WordPress

Here, we want to log in the user via WordPress. That means we want to allow WordPress users to log in the custom script. The solution is quite simple and easy to implement.

Solution

To Log in the user via WordPress in a PHP script, we have to check WordPress sessions in our custom PHP script. However extending the WordPress functionality to a custom script is not a piece of cake.

So instead of extending WordPress login functionality, we have to create a custom session in WP and then check that session in our custom script to check for login.

Just open theme editor in WordPress and copy and paste the below PHP code at the end of the functions.php file to generate a custom session every time admin login to WP.

CODE

add_action('init', 'NewSession', 1);
add_action('wp_logout', 'EndSession');
function NewSession() {
    if(!session_id()) {
        session_start();
	$_SESSION["Name"] = "Value";
    }
}
function EndSession() {
    session_destroy ();
}

Explanation

As we know a session is auto destroyed when the browser is closed. So, the above code will create a session every time any WordPress user logs in. The above-created sessions will be destroyed when the user will log out wp-admin.

Just add your desired session name and value in session you want to verify at a custom script for user validation.

Conclusion

WordPress is effortless to create any blog or website. Also, it is flexible for customization for further development. I hope now you can implement the WordPress login to your custom PHP project.

Enjoy Development 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *

Read previous post:
remove maintenance mode in wordpress
[Solved] Briefly Unavailable for Scheduled Maintenance. Check Back in a Minute

Maintenance mode is one of the most core features of WordPress. Basically this message occurs while updating plugins in WordPress...

Close