blog

Pull Magento User Session Data into Wordpress

published in

Code, Magento, Web Development, Wordpress

comments

11

Often with my Magento ecommerce sites I like to use Wordpress to power the blog and pages as Magento’s CMS is not up to bar and the available Magento blog extensions are still a bit cumbersome. The biggest issue in combining these two is overcoming the problem of maintaining the users session details (cart items, logged in status) that often display globally in a websites header. Wordpress destroys global session variables upon initialization and cookies are not really going to update as a user goes back and forth between Magento and Wordpress – this leaves AJAX as one possible solution. 

We are going to go over how to pull the users session data (status, cart items, name etc) out of Magento and into Wordpress. This will keep the transition between blog and store seamless allowing the user to access their information as if they were still in Magento.

This article is assuming:

  • Magento is installed in the root directory.
  • Wordpress is in a directory such as /blog.
  • Your sites design requires displaying items such as the users name, logged in status, cart items in a global place, such as the header.

Getting the Data From Magento

In the root directory of Magento create a blank php file titled data.php. The first thing we are going to want to do in this file is access mage:

// Access Mage
include_once 'app/Mage.php';
umask(0);
Mage::app("default");
Mage::getSingleton("core/session", array("name" => "frontend"));


Be sure that app/Mage.php is the proper path according to your installation. If you enter the url http://www.yoursite.com/data.php you should see a blank page. If you have an error including Mage.php take note of the path in the error as an incorrect path is usually the most common issue. Next we need to access some data from Magento and store it in variables:

// Store users session
$session = Mage::getSingleton("customer/session");

//Store cart items
$totalNumOfCartItem = Mage::getModel('checkout/cart')->getItemsQty();

Above we are getting the users session and the total items currently in their cart. From here you can test and output a number of different session items – I will show an example of a few possibilities and what can be done. Next in this file we need to output the data. I chose to output the HTML I needed here and store it in a variable to be passed to Wordpress.

// Output Username or Guest
if(isset($_GET['mode']) && $_GET['mode'] == 'mage_welcome') {

        if($session->isLoggedIn()){

                $first_name .= $session->getCustomer()->getData('firstname').' ';
                $last_name .= $session->getCustomer()->getData('lastname').'!';

                $mage_welcome = '<p class="welcome">Welcome, '.$first_name.' '.$last_name.'</p>
                <p class="logout">Not you? <a href="/customer/account/logout">Log Out</a></p>';

        } 

        else {

                $mage_welcome = '<p class="welcome">Welcome! <a href="/customer/account/login">
                Create an account</a> or <a href="/customer/account/login">log in</a></p>';

        }

        // Store in variable for later
        echo $mage_welcome;
}

In the above statement we seeing if the user is logged in. If they are logged in we are getting their first name and last name, if not we are displaying some Welcome text with log in links. The value is then stored in the $mage_welcome variable for use in Wordpress. Below we can see how to check the total items that are in the users cart and store this in a variable called $mage_cart:

// Output cart totals
if(isset($_GET['mode']) && $_GET['mode'] == 'mage_cart') {

        if($totalNumOfCartItem == 0) {

                $mage_cart = 'No items in your Shopping Cart';

        }

        else {

                $mage_cart = '('.$totalNumOfCartItem.' items) in your Shopping Cart';

        }

        // Store in variable for later
        echo $mage_cart;
}

Another one I have used is simply checking to see if the user is logged in or not to display a log in or log out link:

// Output logged in status
if(isset($_GET['mode']) && $_GET['mode'] == 'mage_status') {

        if($session->isLoggedIn()){

                $mage_status = '<a href="/customer/account/logout/">Log Out</a>';

        }

        else {

                $mage_status = '<a href="/customer/account/login/">Log In</a>';

        }

        // Store in variable for later
        echo $mage_status;

}

The users status is then stored in the $mage_status variable for us to use in Wordpress.

Getting the Information from data.php to Wordpress

Next we are going to be using AJAX to get the information from data.php – I credit Brian Lee for assisting me with this script. In your header.php file in your Wordopress theme we will need to place the following script. I am going to give you the entire script and we will discuss one piece of it (most of the script you will not need to change):

<script type="text/javascript">

// Grabs info from data.php for MAGE
function Auto_div(file, mode) {

         var xmlhttp = false;

        try {
         xmlhttp = new ActiveXObject('Msxml2.XMLHTTP');
        }

        catch (e) {
                try {
                        xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
                }

                catch (E) {
                        xmlhttp = false;
                }

        }

        if (!xmlhttp && typeof XMLHttpRequest!='undefined')

         xmlhttp = new XMLHttpRequest();
         xmlhttp.open('GET', file + '?mode=' + mode, true);
         xmlhttp.onreadystatechange=function() {

                if (xmlhttp.readyState==4) {

                        var content = xmlhttp.responseText;

                if( content ) {
                                document.getElementById(mode).innerHTML = content;
                        }

                }

        }

        xmlhttp.send(null)
        return;

}

function init() {

        // Edit these lines with your path to data.php and the name of your variable
        Auto_div('http://<?php echo $_SERVER['HTTP_HOST'];?>/data.php', 'mage_welcome');
        Auto_div('http://<?php echo $_SERVER['HTTP_HOST'];?>/data.php', 'mage_cart');
        Auto_div('http://<?php echo $_SERVER['HTTP_HOST'];?>/data.php', 'mage_status');

}

window.onload = init;

</script>

Take notice to this line in the init function:

// Replace the server path to data.php if necessary
// Duplicate the line above for each variable created in data.php
// and change the variable name in that line
Auto_div('http://<?php echo $_SERVER['HTTP_HOST'];?>/data.php', 'mage_welcome');

You will need to ensure the path to data.php is correct and replace mage_welcome with your variable names without the preceding money sign. What this script is doing is going to make whatever you store in the variables (HTML, integers etc) in data.php accessible by assigning an ID to any element that can have an ID. In your Wordpress theme, for example in my header.php file, we can apply the ID of mage_welcome to a opening div tag:

<div id="login">

        <!-- mage_welcome: outputs from function Auto_div -->
        <div id="mage_welcome"></div>

</div> <!-- End #login -->

The above will output everything from mage_welcome in between the opening and closing tags. Here we have some HTML for the toplinks:

<ul class="top_links">

        <li class="first"><a href="/customer/account/">My Account</a></li>

        <li><a class="top-link-wishlist" href="/wishlist/">My Wishlist</a></li>

        <li><a class="top-link-checkout" href="/checkout/">Checkout</a></li>

        <!-- mage_status: outputs from function Auto_div -->
        <li class="last" id="mage_status"></li>

</ul>

You can see that we simply applied the ID of mage_status to a li and it will output everything from the mage_status variable in between the tags. In the final example, we have applied the mage_cart ID to a anchor tag:

<ul class="top_links">

        <li>

                <!-- mage_cart: outputs from function Auto_div -->
                <a href="http://wildorganics.unleadedsoftware.com/checkout/cart/" id="mage_cart"></a>
        </li>

</ul>

This will output the total number of items in the users cart, if any.

Good luck!

This entry was posted in Code, Magento, Web Development, Wordpress and tagged , , , . Bookmark the permalink.

11 Responses to Pull Magento User Session Data into Wordpress

  1. shua40 says:

    Excellent article. I’m going to give this a try on my next magento/wordpress combo.

    ~S

  2. admin says:

    Let me know how it goes!

    Bret

  3. BD says:

    I’m going to give this a try, too. Do you know how I can load the “topMenu” (product categories) into this data.php so I can pull the category navigation li’s into wordpress?

  4. admin says:

    Hey BD,

    I will post a short article on how to do this in the next few days – hang tight.

    Bret

  5. BD says:

    Thanks for getting back to me. After a bunch of var_dumps, this is the solution I came up with:

    $categories = Mage::helper(‘catalog/category’)->getStoreCategories();

    foreach ($categories as $category){
    $cat_url = $category->getUrlKey();
    $cat_name = $category->getName();

    echo ‘‘.$cat_name.’‘;
    }

  6. BD says:

    er, sorry – your comments ate my pre tag and thus formatted the echo all wrong.

  7. admin says:

    Hey BD, thanks for posting that code and glad you got it figured out! I suppose I should get some code formatting going on these comments ;)

    Cheers,
    b

  8. Cheekius Geekus says:

    Hey there, Bret! Thanks for sharing your knowledge here.
    I have to admit that I’m pretty amazed that you can grab session variables for another application, when I can’t even get Magento to use them in its emails!

    Any idea what the problem could be when my emails say (for example):
    “Dear {{htmlescape var=$customer.name}}”

    I’m running two stores under one Magento installation. Any idea where I have gone wrong?

  9. Bret says:

    Hi there. I doubt the multi store configuration has anything to do with it. To clarify, “Dear {{htmlescape var=$customer.name}}” is what you are seeing printed out in the transactional email that is being sent? What version of Magento?

    Bret

  10. Cheekius Geekus says:

    Thank you for the reply, Bret!
    Yes, that is correct. All of the other variables are being substituted correctly, but they do not have the htmlescape before the var=$whatever.variable

    I removed the htmlescape, hoping that would fix the problem, and it prevented the {{code}} from showing up, but now there is no substitution at all (which is an improvement). I can change the “Dear” to “Hello” or something and it will at least make sense.

    I am on v1.3.2.3
    I believe the “upgrade” to 1.3.2.4 was just a change to one file which i did manually.
    This is a SimpleScripts installation/upgrade on Bluehost. I tried to SimpleScripts upgrade to 1.4 but that didn’t go so well (i now know that a lot of template changes are required to work with 1.4). So I’m just staying at 1.3.2.3/4 at the moment.

  11. Bret says:

    That is strange. On the 1.3 sites it should work with htmlescape: {{htmlescape var=$order.getCustomerName()}

    Has the core been altered in the app/code/core/mage/customer dir? Did this stop functioning after the upgrade to 1.3.2.4? Are the other transaction emails pulling the customer name into the email?

    Bret

Leave a Reply

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

*

You may use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>