Piggybacking WordPress

Let’s say you’re running WordPress.  You use it extensively, your whole team is on it, you have some cool plugins that expand WordPress’ functionality, but now you need a whole different custom application (or five) to run alongside WordPress.  What you don’t need, however, is a second authentication system.  Luckily, you don’t have to have one; you can access WordPress’ authentication system, check the user’s authentication, and if there is none, redirect the user to WordPress login form, have them authenticated, and redirect them back to your application.

The following snippet does exactly that. Obviously, it doesn’t have a lot of functionality, it just outputs the current user’s data if the user is authenticated.  Note that in this example the code is located in a subdirectory of WordPress’ root directory (hence, the ../ in include ‘../wp-config.php’), but it should work from anywhere, as long as wp-config.php is reachable for inclusion.

include '../wp-config.php';
if ($current_user->ID == 0) {
  $location = 'Location: ' . site_url('')
    . '/wp-login.php?redirect_to='
    . urlencode($_SERVER['PHP_SELF']);
  echo "<p>You are not logged in.</p>\r\n";
} else {
  echo "<h2>WP: wp_get_current_user()</h2>\r\n";
  echo "<pre>";
  echo "</pre>\r\n";

Leave a Reply

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