Automatically log in Magento administrator to WordPress administration panel

06.Oct.2014

When integrating Magento and WordPress to work together, it is useful to integrate login as well. This way Magento administrators can log in just in one place and be automatically logged in WordPress as well.

Probably the best way to check if administrator is logged in is in WordPress. To check if Magento administrator is logged in, we just have to use following snippet:

1
2
3
4
5
6
7
8
9
10
11
function is_magento_admin() {
    // Init Mage app
    $magePath = realpath(ABSPATH . '../app/Mage.php');
    require_once($magePath);
    umask(0);
    Mage::app();
 
    // Init session with adminhtml session name
    Mage::getSingleton('core/session', array('name'=>'adminhtml'));
    return Mage::getSingleton('admin/session')->isLoggedIn();
}

Then, we need to make WordPress log in the administrator. Here is the snippet for this functionality:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function login_if_magento_admin() {
    if (!is_magento_admin() || !is_admin()) {
        return;
    }
 
    wp_clear_auth_cookie();
    wp_set_auth_cookie(1);
 
    if (!is_user_logged_in()) {
        // Redirect and finish executing to prevent
        // WP core from messing with auth cookie
        header('location: ' . get_admin_url());
        die;
    }
}

Of course, we must call function login_if_magento_admin once we make sure user is trying to access admin. This can be done on admin_init hook or/and on login page.

Lastly, we must not forget to set Magento cookie path to “/”. Without this, Magento session cookie won’t be accessible to Magento session models from WordPress. This can be done in System -> Configuration -> Web -> Session Cookie Management.

Save the settings and you’re good to go. You can now enjoy using login only in Magento.