Categories
Uncategorized

Capturing the username in WordPress for use in another webapp

Sharing authentication between a WordPress log and a co-resident webapp is handy, but can be a bit of a challenge.

Today I needed to find a way for my webapp to pick up my WordPress username in order to use that as a filter criterion in an SQL query.

A little searching and experimenting led me to the following snippet of code which I put in my WordPress header.php file, just below the  tag.

1
2
3
4
<?php
$user = wp_get_current_user();
setcookie("username", $use-->user_login);
?>

This drops a cookie called 'username' which I can retrieve in my PHP webapp

1
echo "Username cookie is  ".$_COOKIE["username"];

There is no doubt a more efficient way of doing this, like ensuring that it only happens once in the session or attaching it to the login code, which I will explore when time permits.  For the moment this works and I can get on with my webapp!

Later:

A look at the wp-login.php suggests that the place to put this in the login script is in the wp_signon() function of user.php. This approach would be much preferable to putting it in the header – there's no sense in dropping the cookie every time a page is loaded. I'll report back when I've had a chance to test this out.

Leave a Reply