How to use Magento’s session within WordPress

Update (May 11, 2010): I created a WordPress plugin for this one. Check it out here.

You have a free WordPress blog that has been online for sometime. You love its simple yet powerful way of managing your content so you’ve decided to have it hosted to a different provider in order to have a more granular control to its code and functionality. Eventually, you needed cash to support the hosting expenses so you decided to utilize your blog for e-commerce use. That’s when Magento comes in to the scene. You want to find a way to use Magento as your backend while pulling your catalog and customer information to be posted to WordPress site. This is what my article is for.

Since your WordPress will serve as the frontend, you don’t have to worry about where the database for Magento will be located as long as you have a local access to the Mage.php file in order to extend all Magento’s functionality to your WordPress pages. My current setup is still the same with the rest of my post here having ‘htdocs’ as my root directory, magento has its own subdirectory ‘htdocs/magento’ as well as wordpress in ‘htdocs/wordpress’. The goal here is to able to use Magento as if it is a native function within our WordPress installation.

Since there is an existing function collision between Magento and WordPress because both application has an existing translator function named __(), our first task is to automatically detect if the function already exists and disable it in Magento and run as usual if it doesn’t.

To do that, locate the file below in your Magento installation:
Copy the file functions.php below from your Magento core folder

path:to-your-htdocs/magento/app/code/core/Mage/Core/functions.php

and paste it in the Magento local folder which can be found below and open it for editing (create needed folders if it doesn’t exists):

path:to-your-htdocs/magento/app/code/local/Mage/Core/functions.php

Locate the function __() or go to line 93:

function __()
{
    return Mage::app()->getTranslator()->translate(func_get_args());
}

replace it with this:

if (!function_exists('__')) {
	function __()
	{
		return Mage::app()->getTranslator()->translate(func_get_args());
	}
}

Why did I choose to disable Magento’s translator function instead of WordPress’? It is because in Magento, it has already been marked as deprecated in version 1.3 and searching throughout the installation I didn’t see any file that uses that function.

Now that the function collision has been solved, let’s proceed in modifying WordPress to include our Mage.php file. Locate and open the WordPress file below:

path-to-your-root-htdocs/wordpress/wp-includes/functions.php

Scroll down to the end of the file. Add the codes below right after the last function statement which is after line 4122

Note: Mage Enabler plugin users don’t need to do this anymore.

/**
 * Run Magento's Mage.php within WordPress
 *
 * @author Richard Feraro <[email protected]>
 * @link http://mysillypointofview.richardferaro.com
 *
 * @return object
 */
function magento($name = "frontend") {
	// Include Magento application
	require_once ( "../magento/app/Mage.php" );
	umask(0);
	// Initialize Magento
	Mage::app("default");
	return Mage::getSingleton("core/session", array("name" => $name));
}

That’s it! I know it’s weird that it isn’t like the solution given by others that require modifying a lot of files. Nevertheless, I tested it and it does work. You just have to make sure that whenever you use the magento() function to any file within WordPress, always place it at the top most part of the code where there’s no header request or else you will get a similar error below:

Fatal error: Uncaught exception 'Exception' with message 'Warning: session_start() [function.session-start]: Cannot send session cookie - headers already sent by (output started at path:to-your-htdocs\wordpress\wp-content\themes\twentyten\index.php:19) in path:to-your-htdocs\magento\app\code\core\Mage\Core\Model\Session\Abstract\Varien.php on line 115' in path:to-your-htdocs\magento\app\code\core\Mage\Core\functions.php:245 Stack trace: #0 [internal function]: mageCoreErrorHandler(2, 'session_start()...', 'path:to-your-htdocs...', 115, Array) #1 path:to-your-htdocs\magento\app\code\core\Mage\Core\Model\Session\Abstract\Varien.php(115): session_start() #2 path:to-your-htdocs\magento\app\code\core\Mage\Core\Model\Session\Abstract\Varien.php(155): Mage_Core_Model_Session_Abstract_Varien->start('frontend') #3 path:to-your-htdocs\magento\app\code\core\Mage\Core\Model\Session\Abstract.php(84): Mage_Core_Model_Session_Abstract_Varien->init('core', 'frontend') #4 path:to-your-htdocs\magento\app\code\core\Mage\Core\Model\Ses in path:to-your-htdocs\magento\app\code\core\Mage\Core\functions.php  on line 245

An example of how to use this is to check whether a customer is logged in or not. To do this, open the index.php of WordPress’ default theme which is Twenty Ten 0.7:

path-to-your-root-htdocs/wordpress/wp-content/themes/twentyten/index.php

Just below line 15, add the magento() function. It should look like the codes below:

<?php

/**
 * The main template file
 *
 * This is the most generic template file in a WordPress theme
 * and one of the two required files for a theme (the other being style.css).
 * It is used to display a page when nothing more specific matches a query.
 * E.g., it puts together the home page when no home.php file exists.
 * Learn more: http://codex.wordpress.org/Template_Hierarchy
 *
 * @package WordPress
 * @subpackage Twenty Ten
 * @since 3.0.0
 */
 magento(); // Don't add this anymore if you're already using Mage Enabler

?>

<?php get_header(); ?>

Add the code below marked as Magento’s custom greeting right after the get_header() function of WordPress in the same file:

<?php get_header(); ?>
<!-- Magento's custom greeting -->
<div style="font-size: 15px; margin-bottom: 15px; border-bottom: 1px solid #000; padding-bottom: 10px;">
<?php
	$session = Mage::getSingleton("customer/session");
	$magento_message = "Welcome ";
	// Generate a personalize greeting
	if($session->isLoggedIn()){
		$magento_message .= $session->getCustomer()->getData('firstname').' ';
		$magento_message .= $session->getCustomer()->getData('lastname').'!';
	}else{
		$magento_message .= "Guest!";
	}

	echo $magento_message;
	//echo "<br>";
	//print_r($session);
?>
</div>
<!-- End of Magento's custom greeting -->

The purpose of the code change above is to display a ‘Welcome [customer name here]’ when a customer is logged in, and show ‘Welcome Guest’ when they are not.

Next we have to edit the file below to allow us to use the default login page of WordPress as entry point for Magento also. We assumed here that both Magento and WordPress has the same list of user credentials. Your setup maybe different as to which user’s database to use so it’s up to you how to implement it.

path-to-your-root-htdocs/wordpress/wp-includes/user.php

Locate the function wp_authenticate_username_password() and find the similar code below. I found mine at line 108.

	if ( !wp_check_password($password, $userdata->user_pass, $userdata->ID) )
		return new WP_Error('incorrect_password', sprintf(__('<strong>ERROR</strong>: Incorrect password. <a href="%s" title="Password Lost and Found">Lost your password</a>?'), site_url('wp-login.php?action=lostpassword', 'login')));

Right after the code above, add the following code starting at line 111 to make it similar to the code below. This update allows us to run the login request of Magento within WordPress:

	if ( !wp_check_password($password, $userdata->user_pass, $userdata->ID) )
		return new WP_Error('incorrect_password', sprintf(__('<strong>ERROR</strong>: Incorrect password. <a href="%s" title="Password Lost and Found">Lost your password</a>?'), site_url('wp-login.php?action=lostpassword', 'login')));
	// Start Magento
	magento(); // Don't add this anymore if you're already using Mage Enabler
	$session = Mage::getSingleton("customer/session");
	try{
		$login = $session->login($username, $password);
	}catch(Exception $e){
		// Do nothing
	}

Finally, to call the Magento’s logout function, locate the file below and open it:

path-to-your-root-htdocs/wordpress/wp-login.php

Find the switch case statement at line 352. Add the necessary code to make it similar to the code below and save it:

switch ($action) {

case 'logout' :
	check_admin_referer('log-out');
	// Start Magento
	magento(); // Don't add this anymore if you're already using Mage Enabler
	Mage::getSingleton("customer/session")->logout();
	wp_logout();

Now test your WordPress by accessing the homepage at http://localhost/wordpress/. It should display the ‘Welcome Guest’ similar to the image below with a cookie named as ‘frontend’ in your Firebug cookie tab. That is your Magento cookie.

A Test WordPress homepage showing the default welcome message for Magento

A Test WordPress homepage showing the default welcome message for Magento

Clicking the login for WordPress redirects us to the login form like the one below while still showing the ‘frontend’ cookie. Since I have a customer with same credentials on both Magento (Customer) and WordPress (set as Subscriber), all I have to do is to use the username and password to login in the form below.

A Test WordPress login page with a generated Magento cookie

A Test WordPress login page with a generated Magento cookie

At this point, your Magento session should be running with an active customer session. To check if it does, go back to your homepage by clicking the top header text or going to http://localhost/wordpress/. It should display now the welcome message with your customer’s name.

A Test WordPress homepage showing the customer's name in the welcome message

A Test WordPress homepage showing the customer's name in the welcome message

I hope this article will help you get started in using Magento’s functionality within WordPress.

About the author

Richard Feraro is a Magento Enterprise Certified developer from Manila, Philippines with 14 years of solid open-source development experience using Linux, Apache, MySQL & PHP.

Leave a Reply

  1. Thanks for your effort. I like what you did. UI will be trying your solution but the only question I have is if your solution can bring not just the welcome message from magento but the header or footer too

    • Yes, it is possible. Check the code below:

      magento();
      // Magento layout
      $magento_block = Mage::getSingleton('core/layout');
      // Header
      $header = $magento_block->createBlock('Page/Html_Header');
      $header->setTemplate('page/html/header.phtml');
      echo $header->toHTML();
      
      // Your WordPress body container here
      
      // Footer
      $footer = $magento_block->createBlock('Page/Html_Footer');
      $footer->setTemplate('page/html/footer.phtml');
      echo $footer->toHTML();
      • Hi Richard,

        How would you bring the header including navigation and the works over to wordpress? My site is http://www.incego.com/m/gold, which is a slightly modified Modern theme. We have the welcome message, cart, login, etc. links, logo image and catalog navigation and cms links.

        Appreciate any pointers you can provide.

        Stephen

  2. That is a really interesting take on WP/Mage integration. We always use the store itself as the primary for more flexibility and control over the layout (WP is pretty basic!), but a good article nonetheless!

  3. Its perfect. My next question is:
    I need to get the current store id form outside magento. (1 is English and 3 is Spanish).
    In theory, the code I need is:
    require_once ( “../app/Mage.php” );
    umask(0);
    // Initialize Magento
    Mage::app(“default”);
    $idioma = Mage::app()->getLocale()->getDefaultLocale();

    Always return 1 (because is the default, obviusly) It doesnt matter if I have choose Spanish before I open the blog) Its hard to explain, but if you see my page http://www.talkingwebs.net you can understand. If I open home in Spanish (everything will be in Spanish)… if I go to the navigation bar and click on blog.. everything except the “content” (=blog) will be in Spanish (header, footer, sidebar, etc) but the “content will be in English because the code below I have in index.php (wp-content-theme)
    require_once ( “../app/Mage.php” );
    umask(0);
    // Initialize Magento
    Mage::app(“default”);
    $idioma = Mage::app()->getLocale()->getDefaultLocale();

    returns always 1

  4. Richard, awesome post. I just wanted to clarify whether in your example Magento and WordPress are installed into the same database or not.

    Thanks,
    Mike

    • Thanks Michael!

      In my example, WordPress and Magento have a different database for each other. Also it doesn’t matter if they are both in one database, separate database in one location or each located in a remote server as long as WordPress is able to access Mage.php

  5. Pingback: wp-popular.com » Blog Archive » How to use Magento?s session within WordPress ? My Silly Point of View UNITED STATES

  6. all thing is very well.but when i go to the magento site it is already show “Default welcome msg!”
    thanks

    • Are you trying to show the header and footer of Magento to WordPress? If yes, then that’s correct. It’s your HTML block from Magento. Try viewing the source and you will see the output of your .phtml

  7. thanks for your reply.
    i use wamp in windows2003
    and the wordpress in the /wordpress
    magento in the /magento
    and i use the firecookie and found the /wordpress’s cookies path is /wordpress
    /magento’s cookies path is /magento

    perhaps,that is why the headeris different between wordpress and magento .
    thanks

    • The cookie path has nothing to do with it. The output has no styling because of your CSS not present in WordPress. The output is correct based on the default header.phtml found in the directory below:

      path://to-your-magento/app/design/frontend/base/default/template/page/html/header.phtml

      Check the code at the directory below to see how it works:

      path://to-your-magento/app/code/core/Mage/Page/Block/Html

  8. Hi Richard,

    Very timely article for me. I was about to start copying source code into Magento pages. I do have one questions regarding the breadcrumbs Magento’s category navigation. Do you see your method being able to make these features work?

    For example, if am viewing the products of Magento (Home>Store>Accessories) in WP and I click Home in the breadcrumb trail, is it going to take me to WP’s home or Magento’s.

    Thank you for your help and your work.

    • Hello Peaker,

      Yes it can, but the default code will pull Magento’s URL. You can implement your own custom breadcrumb by either pulling the original breadcrumb from Magento and then overwrite portions of URLs (using str_replace()) into your defined pages or you can use the built-in addCrumb() method:

      $breadcrumbs->addCrumb('home',
          array(
              'label'=>'this is home',
              'title'=>'view homepage',
              'link'=>'http://www.your-defined-page.com'
          )
      ); 

      For more details, check the file path://to-your-magento/app/core/Mage/Catalog/Block/Breadcrumb.php

      Thanks :p

  9. What if you don’t want to assume that both Magento and WordPress has the same list of user credentials and that all you want is the global nav (Welcome, John Smith! My Account My Wishlist (1 item) My Cart Checkout Log Out) to display the session info in while viewing WP pages?

    I have skinned my WP and Magento pages to look identical, but the session information therefore does not work. Meaning that when I login (to Magento) and add some products to my cart, that Welcome message reflects the change (My Cart (1 item)), but as soon as I navigate to a WP page, Welcome message does not reflect the change and still states “Welcome Guest!”. I tried following your example to pull in the header and footer from Magento. I was able to do both, but the when I tried to do a similar script to pull in the top.links.phtml, I had no success.

    magento();
    // Magento layout
    $magento_block = Mage::getSingleton(‘core/layout’);

    // TopLinks
    $toplinks = $magento_block->createBlock(‘Page/Html_toplinks’);
    $toplinks->setTemplate(‘page/html/top.links.phtml’);
    echo $toplinks->toHTML();

    // Header
    $header = $magento_block->createBlock(‘Page/Html_Header’);
    $header->setTemplate(‘page/html/header.phtml’);
    echo $header->toHTML();

    Am I going about this wrong?

    • Hi Richard,

      I figured it out. This is awesome! Thank you for your research. Using your example and the thread below, I was able to pull my toplinks session data from Magento into WP. Now customers’ session info is displayed in all my WP pages.

      http://www.magentocommerce.com/boards/viewthread/17459/#t60477

      Here’s my code.

      <!-- Magento's custom greeting -->
      <?php
      if(isLoggedIn()){
      		$magento_message .= $session->getCustomer()->getData('firstname').' ';
      		$magento_message .= $session->getCustomer()->getData('lastname').'!';
      	}else{
      		$magento_message .= "Guest!";
      	}
      
      # Initiate Blocks
      $linksBlock = $magento_block->createBlock("page/template_links");
      
      $checkoutLinksBlock = $magento_block->createBlock("checkout/links");
      $checkoutLinksBlock->setParentBlock($linksBlock);
      
      $wishlistLinksBlock = $magento_block->createBlock('wishlist/links');
      $wishlistLinksBlock->setParentBlock($linksBlock);
      
      
      # Add Links
      $linksBlock->addLink($linksBlock->__('My Account'), 'customer/account', $linksBlock->__('My Account'), true, array(), 10, 'class="first"');
      $wishlistLinksBlock->addWishlistLink();
      $checkoutLinksBlock->addCartLink();
      $checkoutLinksBlock->addCheckoutLink();
      
      if ($session->isLoggedIn()) {
          $linksBlock->addLink($linksBlock->__('Log Out'), 'customer/account/logout', $linksBlock->__('Log Out'), true, array(), 100, 'class="last"');
      } else {
          $linksBlock->addLink($linksBlock->__('Log In'), 'customer/account/login', $linksBlock->__('Log In'), true, array(), 100, 'class="last"');
      }
      
      echo $magento_message.''.$linksBlock->renderView().'';
      
      ?>
      
      <!-- End of Magento's custom greeting -->
  10. hi Richard

    great script! I have an almost solution for my needs.

    just needed to know how I can render childhtml, the code below is whats in my header.phtml

    <a href="getUrl(”) ?>” title=”getLogoAlt() ?>” class=”logo”>
    <img src="getLogoSrc() ?>” alt=”getLogoAlt() ?>” width=”262″ height=”71″ />

    getChildHtml(‘topSearch’) ?>
    getChildHtml(‘topMenu’) ?>

    createBlock(‘Page/Html_Header’);
    $header->setTemplate(‘page/html/header.phtml’);
    echo $header->toHTML();

    does not process these blocks:
    getChildHtml(‘topSearch’) ?>
    getChildHtml(‘topMenu’) ?>

    Thanks

      • sorry that is the correct syntax I have – the form submission seems to have removed the php open tag and the ‘this’ reference

      • I’m having the same issue as James. Both my Header and Footer are constructed of getChildHTML tags. How do I get WordPress to render these?

        Header:

        <div class="header">
        	<?php echo $this->getChildHtml('topLinks') ?>
        	<?php echo $this->getChildHtml('topSearch') ?>
        	<?php echo $this->getChildHtml('logo') ?>
        	<?php echo $this->getChildHtml('topMenu') ?>
        </div>
        

        Footer:

        <?php echo $this->getChildHtml('cms_footer_links') ?>
        <?php echo $this->getChildHtml('footer_links') ?>
        <?php echo $this->getChildHtml('newsletter') ?>
        
  11. This looks really promissing but when trying on WordPress 2.9.2 and Magento 1.4.0.1 I get this horror message:

    Fatal error: Uncaught exception ‘Mage_Core_Model_Store_Exception’ in /home/d32751/public_html/app/code/core/Mage/Core/Model/App.php:1228 Stack trace: #0 /home/d32751/public_html/app/code/core/Mage/Core/Model/App.php(760): Mage_Core_Model_App->throwStoreException() #1 /home/d32751/public_html/app/Mage.php(322): Mage_Core_Model_App->getStore(NULL) #2 /home/d32751/public_html/app/Mage.php(334): Mage::getStoreConfig(‘web/url/use_sto…’, NULL) #3 /home/d32751/public_html/app/code/core/Mage/Core/Controller/Request/Http.php(196): Mage::getStoreConfigFlag(‘web/url/use_sto…’) #4 /home/d32751/public_html/app/code/core/Mage/Core/Controller/Request/Http.php(148): Mage_Core_Controller_Request_Http->_canBeStoreCodeInUrl() #5 /home/d32751/public_html/app/code/core/Mage/Core/Model/App.php(379): Mage_Core_Controller_Request_Http->setPathInfo() #6 /home/d32751/public_html/app/code/core/Mage/Core/Model/App.php(262): Mage_Core_Model_App->_initRequest() #7 /home/d32751/public_html/app/Mage.php(570): Mage_Core_Model_App->init(‘default’, ‘st in /home/d32751/public_html/app/code/core/Mage/Core/Model/App.php on line 1228

    Any ideas?

    • Check the permission of the following folders:

      /app/etc
      /media
      /var
      

      Magento must have read/write access to these folders. Also clear the sessions and cache folder contents within /var.

  12. Is anybody gettting this to work with Magento 1.4.0.1 and WordPress 2.9.2? I get a fatal error. Maybe it needs to be altered for these versions?

  13. hi Richard

    I have solved the immediate problem by moving the nav blocks to outside the header area and referencing the html createBlock seperately

    However I still have some inner htmls in the header block which is not being rendered getChildHtml('seo.searchterm') ?>

    Also another one in footer getChildHtml('seo.searchterm') ?>

    Any thoughts on why any of the html inner blocks are not being redered?

    • I have used the code tag to paste the code but the wp seems to truncate my opening php tag, echo statement and the class refrence. Am I doing somethign wrong?

      • Hi Richard

        Thanks for taking the timur e to respond to my queries.

        My script is working is all ok and works fine on my magento rendered pages. The issue is only in the word press header.

        Re-pasting my code using your instructions:

        <div id="header">
        	<div id="logo">
        		<a href="<?php echo $this->getUrl('') ?>" title="<?php echo $this->getLogoAlt() ?>" class="logo">
        			<img src="<?php echo $this->getLogoSrc() ?>" alt="<?php echo $this->getLogoAlt() ?>" width="262" height="71" /></a>
        	</div>
        
        	<div id="basketPanel">
        		<?php echo $this->getChildHtml('topLinks') ?>
        
        		<a href="<?php echo $this->getUrl('checkout/cart') ?>">
        		<img src="<?php echo $this->getSkinUrl('images/basket.png') ?>" alt="Shopping Basket" width="79" height="23"></a></td>
        
        		<a href="<?php echo $this->getUrl('checkout') ?>">
        		<img src="<?php echo $this->getSkinUrl('images/checkout.png') ?>" alt="Basket Checkout" width="79" height="23"></a></td>
        	</div>
        </div>
        
  14. Thanks for the feedback! I’ve tried to change the permissions as you suggest and also clear seassion and cache data but still the same error. In fact I’ve tried to chmod 777 the whole site but still the same error.

    In the past I’ve had some errors because my server run php as a module. Could this cause errors?

  15. Sorry to bother you with these boring errors. This time I’ll only give you some feedback.

    1, I did get the code running! But I didn’t change the code. Instead I tried it from my Macbook which uses another version of Firefox and to my surprise it started working! When I however try from Safari on the Macbook it still gives me the same error.

    2. I did a fresh install of Magento 1.4.0.1 through ssh on the same server (I think I used ftp last time). This time I get the code working again (all browsers).

    I don’t know what conclusions to draw but I just wanted to leave some feedback.

  16. Ha, nailed it!!!

    The problem lies in the internal Store View Codes. I run three stores and I’ve changed the Store View Codes to make sense to me. While doing that I removed the Code ‘default’. So when I put ‘default’ back it starts working. Magic!

    Many thanks for great feedback and code examples!

  17. Richard,

    Do you have any ideas on how you could query both Magento and WP’s db at the same time, so that the search function will return posts and catalog items?

    • Hi Peaker,

      Why would you want to combine two different sets of data into 1 query? Create a separate query for post and catalog then do your manipulation in arrays using PHP.

  18. I have a question.

    This work-around may solve my problem.

    I have a website (Xhtml/css). I need to add Magento to it as well as a CMS for the static & blog pages (more static pages then blog).

    I am considering putting my website into WordPress. And then creating a Magento site/theme that looks just like it. So it would be mywebsite.com and shop.mywebsite.com

    On my homepage I need to pull magento products into a slider/carousel. Will this workaround help with that?

    I also need to have the header and footer from Magento. (ie “Log-in/Register” and “Your cart has 2 items”).

    Is this even the best method.

    • Hello Erica!

      You want to use WordPress for the homepage with the login/register and cart info in it pulling information from Magento while the subdomain ‘shop’ will showcase an actual Magento store? Yes, it is possible πŸ™‚ Although you will be managing two sites now since Magento has its own templating system. How about using WordPress for everything from blogging to the actual shop too so that all you need to skin is WP (who in turn handles your CMS and shop’s frontend) and catalogs and orders management will be handled at the backend of Magento?

  19. Richard,

    So I will be able to do front-end WP and back-end Magento with this workaround?

    Just so I understand. Inside a WP template I can have my Magento products displayed on the page. I can interact with Magento as I normally would inside of WP?? If, so this sounds like the solution to my problem. I think I struggle with the logic more than anything.

    • Yeah, you’re right. It’s more like you just have to create your pages for the required functionality from Magento to WordPress pages such as product display/search, viewing product details, cart functions and customer related tasks. I did a similar project last year but instead of using WordPress, I used CodeIgniter framework while Magento would be my backend. Everything can be done thru Mage.php file πŸ™‚

  20. Hey Richard,

    Thanks for taking the time to post this article – exactly what I am looking for. I have ran through the article a couple times and have a couple questions:

    1. To keep from modifying the core of WP can I assume it would be okay to place the magento() function inside functions.php of my theme? (I did similar by making the change to magento’s functions.php in code/local/Mage/Core).

    2. In WordPress (2.9) mage is working and I can print_r the session object but I can not seem to access any data from mage (user name, cart items etc) – I simply get nothing. Magento is 1.4.0.1.

    Any Suggestions?

    Kind Regards,
    Bret

    • Hi Bret!

      Thanks for reading my blog. Regarding item number 1, it really doesn’t matter whether you place your magento() function inside functions.php or within your theme files as long as you get the same result. I just placed it within functions.php for it to be available anywhere within WordPress, not just my theme files. Just make sure that no header has been sent prior to calling the ‘core/session’ of Magento.

      For your item number 2, how do you use the script for accessing customer info and cart contents? You should be able to access it already since the session’s object can be printed as you mentioned earlier. Check as well the error_reporting of your php settings. It must be set to ‘all’ while in development stage so you can see if there’s an error in your script.

      Regards and good luck!

  21. Hi Richard!

    Great idea for wordpress integration. This looks so simple that it is hard to believe!
    So it is really possible to pull everything in Magento into WordPress?
    Even payment modules? It would be really cool to find a live example.

    Pure genius!

    • Thanks for the feedback!

      Yes, you should be able to utilize the payment modules present in Magento to your WordPress instance. For example, the script below can be used in order to pull the list of active payment methods from Magento to WordPress:

      magento();
      // Get collection of active payment methods
      $activepayments = Mage::getSingleton('payment/config')->getActiveMethods();
      // Create the initial dropdown option
      $methods = array(array('value'=>'', 'label'=>Mage::helper('adminhtml')->__('--Please Select--')));
      
      // Loop through active payment list and push it to $methods array
      foreach ($activepayments as $paymentCode=>$paymentModel) {
          $paymentTitle = Mage::getStoreConfig('payment/'.$paymentCode.'/title');
              $methods[$paymentCode] = array(
                  'label'   => $paymentTitle,
                  'value' => $paymentCode,
              );
      }
      // Generate dropdown
      echo "<br><br>";
      echo "<select name=\"active_payments\">";
      foreach($methods as $key => $value){
      	echo "<option value=\"".$value['value']."\">".$value['label']."</option>";
      }
      echo "</select>";
      

      This should produce an output like the one below:

      Sample dropdown list of Magento?s active payments within WordPress

      You may check your other options in the Magento docs πŸ™‚

  22. Hi Richard,

    I just stumbled upon your post and I must say it looks really great.
    I am going to give it a try today.
    If it works as expected this is awesome. Do you plan to release it as a WP plugin anytime? That would be a really popular one, no doubt.
    Thanks again.

    • Hello Olivier,

      Thanks for reading my blog. Actually that is my next target article. I’m just figuring out for a couple of days already how I can make it work seamlessly via ‘hook’ in WP processes without getting ‘cannot send header…’ error. Hopefully I can finish it soon.

      Let me know if it works for you πŸ™‚

  23. Pingback: Mage Enabler: A plugin to run Magento’s session within WordPress « My Silly Point of View UNITED STATES

  24. Currently using WordPress (3.0-beta2-14729)
    and
    Magento 1.4

    WordPress is here:
    http://www.pffmaui.com/blog/
    and Magento is here:
    http://www.pffmaui.com/

    I followed your steps and implemented all the code etc.

    Also, uploaded the mage enabler to here:
    /html/blog/wp-content/plugins/mage-enabler

    When I tried to activate plugin – it gave me “The plugin does not have a valid header.” error.

    Also, when I try and link to sub-page for blog – the page comes up empty:
    http://www.pffmaui.com/blog/plumeria

    thanks for all your support.
    Aloha,
    Greg

    • UPDATE:
      Was able to change the path from this:
      /**
      * Run Magento’s Mage.php within WordPress
      *
      * @author Richard Feraro
      * @link http://mysillypointofview.wordpress.com
      *
      * @return object
      */
      function magento($name = “frontend”) {
      // Include Magento application
      require_once ( “..magento/app/Mage.php” );
      umask(0);
      // Initialize Magento
      Mage::app(“default”);
      return Mage::getSingleton(“core/session”, array(“name” => $name));
      }
      to this:
      /**
      * Run Magento’s Mage.php within WordPress
      *
      * @author Richard Feraro
      * @link http://mysillypointofview.wordpress.com
      *
      * @return object
      */
      function magento($name = “frontend”) {
      // Include Magento application
      require_once ( “../app/Mage.php” );
      umask(0);
      // Initialize Magento
      Mage::app(“default”);
      return Mage::getSingleton(“core/session”, array(“name” => $name));
      }

      The “Welcome Guest” message comes up on the pages where I placed it, but it doesn’t update when person is logged in.

      Thanks again,
      Greg

    • Do not edit functions.php anymore if you have the Mage Enabler plugin installed. I also checked your site, the ‘frontend’ cookie is properly generated which means Mage object is instantiated.

  25. OK –
    Removed the added functions.php file:
    app/code/local/Mage/Core/functions.php

    Tried to activate the plugin and received following error message:

    The plugin does not have a valid header.

        • Which is wrong. If you check the Mage Enabler folder setup image, there’s no mage-enabler folder inside plugins/mage-enabler but rather the actual files including the main php file. In your setup, the main php file is found in plugins/mage-enabler/mage-enabler/mage-enabler.php

        • Yes – jumped back a folder and now the install works.

          What code do I need to input to get the Welcome messge to show up?

          Thanks again,
          Greg

        • You might wanna consider making sure which of the two domain (www.pffmaui.com or pffmaui.com without the ‘www’) you want to use because each will create a different cookie and might get some shopping cart issues on this. I checked your site just now and saw two ‘frontend’ cookies for ‘.pffmaui.com’ and ‘.www.pffmaui.com’ πŸ™‚

  26. Hi Richard,

    Great article! I’m trying to get my head around how to build a wordpress site with a magento backend and this has been a great starting point.

    One problem I can see though – how di I get the same users in both the magento database and the wordpress database?

    Thanks,

    Jim

    • Hello Jim,

      Thanks for reading the article. Regarding your question, the setup will vary depending on your project. You can maintain the separate databases for customers (Magento) and subscribers (WordPress) or you can ditch one of the two users table so you have only one source of user profiles. In the article I wrote, I assumed that the programmer who will be using the technique shall devise a way to sync the two user database; either hacking some WordPress function that creates the user record to pass the same parameters to Magento’s method that creates the user, or the other way around. Since the Mage object already runs within WordPress, it shouldn’t be hard communicating between the two application.

      For testing purposes, I manually created the customer and subscriber account with the same login details on both Magento and WordPress to see if it works.

      Thanks πŸ™‚

      • Thanks Richard, just being lazy I guess πŸ™‚

        You’re right – with the Mage object working from wordpress should be able to create magento users from within the wordpress create user code.

        Again – great article!

        • First, Richard, thank you so much for this information! I installed plugin, thank you.

          Now, Jim, can you say, are you going to do this? I have big WordPress site with 15,000 subscribers. I think I can easily import these to Magento, but how when new WP subscribers create account will they automatically be created in Magento as well?

          Thank you, Jim, Richard, for any advice you can provide. Meanwhile I will be looking at Magento’s customer creation markup to hopefully find what I need to put into WordPress.

          Cheers!
          Joe

  27. Now THIS looks interesting. Not sure how, what with all of the searching I’ve been doing over the past weeks, I missed this. All I see is “WordPress in Magento”, “WordPress in Magento”, “WordPress in Magento”, “WordPress in Magento”. Maybe it’s just a matter of semantics but I *think* I prefer it the way you’ve done it. I read through the other two posts and comments and I am heartened by reading that someone is using WP3, so there’s hope for what I want to do, ‘cuz I’m in WPMu in a subdomain install.

    Currently, I’m working in a sandbox install of WPMu testing carts. I’ve invested a week rewriting sections of WP e-Commerce so that it works but the pervading atmosphere of frustrated users is beginning to make me lose my Fools Rush In approach to it and find a more robust pairing. I’m at the point of buying the addons that are required to actually make it do what it should and I’m seeing that when *that* happens, it opens up another whole can of landmines that’ll have to be overcome. The atmosphere here and the level of clue has me enthused again, but in starting over, not in continuing down the same path. I can always fall back on that work if I need it but I gotta find out how your solution works.

    Anyhoos, before I go and bork my well-oiled machine (and I’m really chomping at the bit to try this out) it would be prudent to ask the one person who would know.

    My set up:
    WPMu 2.9.2
    Subdomain install in /public_html root
    Domain Mapped main and sub-blogs

    a) Will Mage Enabler play well with WPMu and be able to access the one Magento install from different WP themes?

    b) Can Magento be installed in a parallel directory such that I have:
    /public_html/WPMu/
    /public_html/WPMu/wp-[subs]
    Magento would go in:
    /public_html/shop/
    /public_html/shop/subs
    From the absolute path specs required, I’m guessing ‘yes’.

    I’d use a separate database, partly due to just keeping things compartmentalized and partly due to Magento requiring InnoDB tables; which I have no experience with.

    c) I have the Sitewide Tags blog running on the parent. If the answer to ‘a’ is yes, can I pull items from sub-blog shops into one shop and/or pull items from one sub-blog shop into another sub-blog shop? (This one might be stretching it but…)

    Thanks, and thanks or your great work.

    • Hello BJ πŸ™‚ Thanks for taking time reading my articles.

      Here are my answers to your questions:
      a. Yes, as long as you have a local access (absolute URL) to your Mage.php file.
      b. Yes, whether the shop is within WPMu directory or same directory level as your WPMu it should work properly. InnoDB is almost the same as MySQL only that InnoDB’s way of handling, saving, storing records are favorable for transactional data.
      c. Yes, it’s possible. The way you access ‘items’ will depend on how they are stored. For example, if they are from different databases then you wouldn’t have problem as long as your query is executed within the right database. If you’re Magento shop subs uses single database and are grouped by store ID then you can just include the specific store ID to your query so you’ll be able to differentiate from which sub the data are from.

  28. Thinking about the domain relationship, URL structure and directory structure it may make more sense in all of those to install Magento as a sub-directory of WPMu:

    /public_html/WPMu
    /public_html/WPMu/wp-[subs]
    /public_html/WPMu/shop/
    /public_html/WPMu/shop/subs/

    This way the primary URL for WPMu can just point to the shop as: http://example.com/shop/ without any rewriting, etc.

    • I’d rather install Magento shop outside your WPMu so I don’t have to worry about messing up each others redirection rules (Magento and WordPress have different URL patterns.) You can still make WPMu point to http://example.com/shop/ using 301 redirect or if you’re in linux, you can use symbolic links to point it to the proper directory. This is just a suggestion and you can still do what you mentioned above if it suits your setup. The good thing about Mage Enabler plugin, it treats any website as an external site so whatever actions you’ll be doing with the Mage object, it will always refer back to the domain (due to it’s cookie) where it is accessed from.

  29. Hi Richard,

    Thanks for the clarifications. So, here’s where it gets natty. Just want to make sure I understand fully. I’m on FreeBSD so a ln will work. In fact that’s how I’m running the two WPMu installs with one set of themes. Tried to do the same with /plugins but some of them couldn’t find their parts, so just gave in and copied.

    I’d install Magento in /public_html/shop/ and set a link from /public_html/WPMu/shop/ to it? Or, does it matter if WP is the parent and Magento is in the background; not accessed directly through a URL? Not sure whether I’d access directly or not but it is a possibility. Perhaps the search engines would need to go there and not go through WP to do it?

    Hmmm… OK I’m now wondering about the redirection rules you speak of. Are you talking internal or in .htaccess? It occurs that direct access to Magento in my case wouldn’t be easily doable, as the parent WPMu domain controls the IP#, so it can handle the domain mapping of sub-blogs pointed at it via A records. Rewrite could handle it, I suppose, but that always does my head in.

    This may be out of your area but regarding SSL, referencing your saying the Mage object always refers back to the domain it is accessed from, do you think I’d have to get one of those really expensive ‘any domain’ (not wildcard subdomain) certs in order to access Magento from the domain mapped sub-blogs? Unless, somehow Magento can have its cert on the parent WP blog and interface with the sub-blogs without throwing browser warnings. The only portion of the purchase process that really has to be SSL is Checkout after collecting contact data, I suppose. Having the whole process within SSL, though, helps customers to feel more protected when they are entering their address, etc.

    • I’d install Magento in /public_html/shop/ and set a link from /public_html/WPMu/shop/ to it? Or, does it matter if WP is the parent and Magento is in the background; not accessed directly through a URL? Not sure whether I’d access directly or not but it is a possibility. Perhaps the search engines would need to go there and not go through WP to do it?

      The setup where Mage Enabler applies is when you wanted to use Magento’s admin to manage the store and WordPress serves as the front-end where you display the products and other stuff from Magento which means the default store front-end wont be seen in any case. The only requirement of the plugin is to have the absolute (explicit file location, definitely the files stored on the same server, but database can be anywhere) location like for Windows it will be C:\xampp\htdocs\magento\app\Mage.php or with Linux it is /public_html/folder/to/your/file.php.

      Hmmm… OK I’m now wondering about the redirection rules you speak of. Are you talking internal or in .htaccess? It occurs that direct access to Magento in my case wouldn’t be easily doable, as the parent WPMu domain controls the IP#, so it can handle the domain mapping of sub-blogs pointed at it via A records. Rewrite could handle it, I suppose, but that always does my head in.

      I mean the format of the URL. WordPress has it own permalink pattern like http://example.com/month/day/sometimes-long-title-here/?#commentid while Magento has http://exampleshop.com/index.php/some-weird-item-with-additional-info-as-filename.html. WP and Magento each has it own htaccess which could extend and affect the subdirectories within it.

      …Mage object always refers back to the domain…

      This is best explained in my previous comment which can be found here.

      …do you think I?d have to get one of those really expensive ?any domain? (not wildcard subdomain) certs in order to access Magento from the domain mapped sub-blogs?

      If you’re sub-blogs belongs to the same domain like http://example.com/blog1, http://example.com/blog2, a single SSL cert is sufficient. But if each sub-blogs is accessed to a different domain even if hosted on the same server and directory like http://exampleblog1.com, http://exampleblog2.com then it will require its own SSL certificate. There are multi-domain SSL cert available, but I think it’s overkill if there are only 10 sites that will use that.

  30. Hi Richard

    I have a number of jquery libraries I load on the magento site which as part of my header display, needs to be loaded in wordpress header as well.

    Magento as you are aware consolidates and creates one js file. I am trying to work out if I can call any functions to display the js file in wordpress header. My intial attempt has been to see if I can get the getCssJsHtml() called by doing this:

    $head = $magento_block->createBlock(‘Page/Html_Head’);
    echo $head->getCssJsHtml();

    but this gives me an error as that function references an object that doesnt seem to be instantiated.

    Am I on the right track with this or going about this the wrong way completely?

    Thanks

    • Hi James,

      Did you try adding the code below at the top of the PHP file you’re working on? This code generates the frontend cookie needed by Magento as well as instantiates the Mage object within WordPress.

      if(class_exists('Mage')){
          Mage::getSingleton('core/session', array('name' => 'frontend'));
      }

      Thanks for checking out my blog πŸ™‚

  31. Oops I seem to have replied to an earlier thread!! Aplogies… meant to go in here

    Correct Richard, this is in my function call of magento();
    P.S Enjoy using your blog and I am a returning blogger ? you have helped me before πŸ˜‰

  32. Some additionla info – The error I am getting when accessing the getCssJsHtml()

    Fatal error: Uncaught exception 'Exception' with message 'Warning: Invalid argument supplied for foreach() in D:\webserver\site\public_html\app\code\core\Mage\Page\Block\Html\Head.php on line 166' in D:\webserver\site\public_html\app\code\core\Mage\Core\functions.php:247 Stack trace: #0 D:\webserver\site\public_html\app\code\core\Mage\Page\Block\Html\Head.php(166): mageCoreErrorHandler(2, 'Invalid argumen...', 'D:\webserver\si...', 166, Array) #1 D:\webserver\site\public_html\thezone\wp-content\themes\site\header.php(55): Mage_Page_Block_Html_Head->getCssJsHtml() #2 D:\webserver\site\public_html\thezone\wp-includes\theme.php(996): require_once('D:\webserver\si...') #3 D:\webserver\site\public_html\thezone\wp-includes\theme.php(974): load_template('D:\webserver\si...') #4 D:\webserver\site\public_html\thezone\wp-includes\general-template.php(34): locate_template() #5 D:\webserver\site\public_html\thezone\wp-content\theme in D:\webserver\site\public_html\app\code\core\Mage\Core\functions.php on line 247
    
    • Hi Richard

      Not much luck so far.

      Btw do you think the Page/Html_Head is acceptable in this call:
      $head = $magento_block->createBlock(?Page/Html_Head?);

      Thanks

      P.S Apologies for the seperate posts rather than replies earlier ( I did a FF upgrade which caused this and requred a restart! )

        • Hi Richard

          Here is a my entire code:

          <?php magento(); ?>
          
          <?php
          	$session = Mage::getSingleton("customer/session");
          	$magento_block = Mage::getSingleton('core/layout');
          	
          	$head = $magento_block->createBlock('Page/Html_Head');
          
          	$header = $magento_block->createBlock('Page/Html_Header');
          	$header->setTemplate('page/html/header.phtml');
          
          	$topSearch = $magento_block->createBlock('Core/Template');
          	$topSearch->setTemplate('catalogsearch/form.mini.phtml');
          
          	$topMenu = $magento_block->createBlock('Catalog/Navigation');
          	$topMenu->setTemplate('catalog/navigation/top.phtml');
          ?>
          
          <html>
          <head>
          	<?php echo $head->getCssJsHtml() ?>
          </head>
          
          </body>
              <?php echo $header->toHTML() ?>
          	<div id="navigation">
          		<?php echo  $topSearch->toHTML() ?>
          		<?php echo  $topMenu->toHTML() ?>
          	</div>
          		
          </body>
          </html>
          

          To confirm all other function calls work except getCssJsHtml() which is giving me the error mentioned above.

          Thanks
          James

        • Saw your multiple comments so I just approved this one since the other 5 comments has the same content πŸ™‚

          Did you forget to add setTemplate() for $head?

          I’ll be trying to come up with a post also on how to pull blocks and static content from Magento maybe this week once I’m done setting up my demo magento in my new machine.

        • When I try to use James’ code with Richard’s additional $head -> setTemplate, Magento spits out the following error:

          Fatal error: Uncaught exception 'Exception' with message 'Warning: session_start() [<a href='function.session-start'>function.session-start</a>]: Cannot send session cache limiter - headers already sent
          
        • Brady you can’t use the whole script which James posted particularly the line which has magento() because James isn’t using Mage Enabler. If you read the whole article above, you will notice there are two ways to implement Magento’s session within WordPress. The original was editing Magento’s functions.php file which James initially used. To improve the code, I created Mage Enabler which does the same thing that editing functions.php does. This means you can only use one of the two methods preferrably Mage Enabler. If you’re using Mage Enabler, you have to remove magento() since the plugin does this for you already. Using Mage Enabler, you have to stick with using the code below:

          if(class_exists('Mage')){
          	// Write your Magento codes here
          }

          You encountered that error because the code below generates a cookie (this is the same code which magento() executes):

           if(class_exists('Mage')){
           	Mage::getSingleton('core/session', array('name' => 'frontend'));
           }

          You’re code should look like this if you’re using James code with Mage Enabler:

          <?php 
          if(class_exists('Mage')){
                  // Place this at the top of the file you're working on to prevent
                  // 'headers already sent' fatal error
           	Mage::getSingleton('core/session', array('name' => 'frontend'));
          }
          ?>
          
          <?php
          if(class_exists('Mage')){
          	$session = Mage::getSingleton("customer/session");
          	$magento_block = Mage::getSingleton('core/layout');
          
          	$head = $magento_block->createBlock('Page/Html_Head');
          
          	$header = $magento_block->createBlock('Page/Html_Header');
          	$header->setTemplate('page/html/header.phtml');
          
          	$topSearch = $magento_block->createBlock('Core/Template');
          	$topSearch->setTemplate('catalogsearch/form.mini.phtml');
          
          	$topMenu = $magento_block->createBlock('Catalog/Navigation');
          	$topMenu->setTemplate('catalog/navigation/top.phtml');
          }
          ?>
          
          <html>
          <head>
          	<?php if(class_exists('Mage')){ echo $head->getCssJsHtml(); }?>
          </head>
          
          <body>
              <?php if(class_exists('Mage')){ echo $header->toHTML(); } ?>
          	<div id="navigation">
          		<?php if(class_exists('Mage')){ echo  $topSearch->toHTML(); } ?>
          		<?php if(class_exists('Mage')){ echo  $topMenu->toHTML(); } ?>
          	</div>
          
          </body>
          </html>
  33. Hi Richard,

    Thanks so much for this tutorial! I ALMOST have it working, but my entire header and footer are built using the ‘getchildhtml’ function, which for some reason isn’t working.

    My directory structure is setup so magento is in the root of my public_html folder and then a wordpress folder inside of that. It seems to work fine, except for URL rewrites in WordPress.

    Here is my header and footer:

    Header

    <div class="header">
    <?php echo $this->getChildHtml(‘topLinks’) ?>
    <?php echo $this->getChildHtml(‘topSearch’) ?>
    <?php echo $this->getChildHtml(‘logo’) ?>
    <?php echo $this->getChildHtml(‘topMenu’) ?>
    </div>

    Footer

    <?php echo $this->getChildHtml(‘cms_footer_links’) ?>
    <?php echo $this->getChildHtml(‘footer_links’) ?>
    <?php echo $this->getChildHtml(‘newsletter’) ?>

      • Meaning I have to define getChildHtml because WordPress doesn’t know what that is?

        I tried to include the getChildHtml function definition in abstract.php, but it didn’t do anything in WordPress.

        function getChildHtml($name='', $useCache=true, $sorted=false)
            {
                if ('' === $name) {
                    if ($sorted) {
                        $children = array();
                        foreach ($this->getSortedChildren() as $childName) {
                            $children[$childName] = $this->getLayout()->getBlock($childName);
                        }
                    } else {
                        $children = $this->getChild();
                    }
                    $out = '';
                    foreach ($children as $child) {
                        $out .= $this->_getChildHtml($child->getBlockAlias(), $useCache);
                    }
                    return $out;
                } else {
                    return $this->_getChildHtml($name, $useCache);
                }
            }
        
        • Meaning I have to define getChildHtml because WordPress doesn?t know what that is?

          No. What I meant was first, are you using the tweak I wrote about in this post or are you using Mage Enabler found in my other post?

        • Hi Richard,

          Thanks for the help with this issue.

          When you say the “tweak” in this post, are you referring to removing the Magento function “__()”, if so, then yes I have.

          I’m also using the WordPress plugin Mage Enabler and the plugin is reporting it found Mage.php successfully.

        • Hi Brady,

          I’m setting up my new machine for magento testing. I’ll let you know what comes up in my own testing for pulling blocks from magento.

          Thanks πŸ™‚

  34. Hi Richard,

    Just tried your code above (right under “You?re code should look like this if you?re using James code with Mage Enabler:”).

    It pulls in Magento’s nav and search box, but leaves everything unstyled and doesn’t appear to follow the getChildHTML commands. The source code shows nothing in within the .

  35. Hi Richard,

    A couple things I noticed in your code:

    1) I believe line 32 should be , not
    2) Line 29 I changed to:

    <?php if(class_exists('Mage')){ echo $head->toHtml(); }?>

    . It pulls in all the header info now, but does not pull in the CSS or JS, which in my head.phtml is called using

    <?php echo $this->getCssJsHtml() ?>
  36. Has anyone got this plugin to work on their site in WordPress? Also, when users go to the shop page are they going to be redirected to magento’s theme? I just want to pull in the products page, product page, and shopping cart page into WordPress and make it seamless. From what I’ve read (and I’ve skimmed so please direct me to where I can find it) when the user goes into the shop they have to actually go into Magento instead of being able to stay within WordPress.

    Any clarification is greatly appreciated.

    • From what I?ve read (and I?ve skimmed so please direct me to where I can find it) when the user goes into the shop they have to actually go into Magento instead of being able to stay within WordPress.

      If you’re referring to Mage Enabler plugin for WordPress, the answer is no. It is a WordPress plugin, so all the communication to Magento is done via PHP scripts written in the theme or non-admin files of WordPress. From which article did you read that?

  37. Hi thanks for a nice script idea. Just wondering in a similar way is it possible to use Joomla Session to authenticate WordPress users?

    Any hints ?

    Thanks in advance.

  38. I’m running WP3+ in multisite mode and although the plugin works as expected in the theme files, the plugin wasn’t initialized and hence the code didnt work in wp-login.php and user.php. So I changed the following code:

    !is_admin() ? add_action( ‘wp’, ‘mage_enabler’ ) : ”;

    to:

    !is_admin() ? add_action( ‘init’, ‘mage_enabler’ ) : ”;

    This seems to have fixed my issue. Do you foresee any problems with this change?

    • Hello VinnyD πŸ™‚

      The only reason that I used wp instead of init is that when I tested Mage Enabler before using the latter hook, it triggered the Cannot send session cookie - headers already sent error on my end. If it works for you, that’s okay. Just double check your previous Magento scripts if it’s not affected by the changes you did πŸ™‚

      It should work within wp-login.php and user.php. What’s the script that you think isn’t working within those files without changing the original hook_name?

  39. Thanks for the prompt reply!

    Basically, in user.php and wp-login.php, the Mage class does not exist. I can not execute the code in the following if statement:

    if(class_exists(‘Mage’))
    {
    //does not run any code in here
    }

    • Hmm, once you enable Mage Enabler, it should be present in any file. Try adding error_reporting(E_ALL) at the top of user.php and wp-login.php to see what’s preventing Mage object from being instantiated. The possible cause could be that Mage::getSingleton("core/session", array("name" => "frontend")); is executed in header.php instead of index.php of your theme file.

  40. Hi Richard, first of all thank you for the great tutorial!

    I am having some problems with accessing Magento session object from the WordPress header, here’s the code I am using:

    $mageFilename = realpath(‘../shop/app/Mage.php’);
    require_once( $mageFilename );
    umask(0);

    Mage::app();
    Mage::getSingleton(‘core/session’, array(‘name’ => ‘frontend’));
    $session = Mage::getSingleton(‘customer/session’, array(‘name’ => ‘frontend’));
    if(session->isLoggedIn())
    echo ‘LOGGED IN’;
    else
    echo ‘NOT LOGGED IN’;

    var_dump($session); return;

    The problem is that my customer session is always showing that the customer is NULL, and the that prints is always NOT LOGGED IN one, even though I am logged in as a Magento customer.

    Otherwise, calling Mage functions from WP works fine. I am using Magento 1.4.0.1 and WP 3.0.4.

    Have you ever came across this kind of problem?

    Best regards,
    Relja

    • Hello Relja,

      Remove the array(β€˜name’ => β€˜frontend’) in your customer getSingleton(). It should look like the code below:
      $session = Mage::getSingleton("customer/session");
      then add a login request right after the code above:
      try{
      $login = $session->login($username, $password);
      }catch(Exception $e){
      // Do nothing
      }

      If your username and password is correct, your isLoggedIn() should echo LOGGED IN.
      You should also keep in mind that if you logged in to Magento frontend, dont expect that you’ll be logged in automatically in your WP since they’re both using a different cookie path. In order for Magento and WP to share the same session, you should pass the PHPSESSID in your URL from Magento to WP or the other way around.

  41. Hi, thanks for the reply πŸ™‚

    The thing is, the users on the blog site can’t do anything and there’s no need for them to be logged in to WordPress, just to Magento. And the idea is for them to be able to see their cart contents while reading some posts on the WordPress site.

    The login command works great, but in order to do it i need to transfer username and password from the Magento site. Is that login still necessary?

    Best regards,
    Relja

    • The login script I posted is for you to test if Mage session is working as expected in your WordPress. Once you have confirmed that indeed they can execute login within your WP (that is if isLoggedIn() returns true), then the next thing you should do is pass the PHPSESSID from Magento to WP for them to share the same session without the use of the login code I mentioned.

  42. Hi Richard. Great plugin! This is going to be incredibly useful for me.

    I posted a question in the plugin forum, but then found that VinnyD was having the same issue a few comments back. I made the same change that he did, and now mine is working as well. Before that, Mage couldn’t be found in wp-login.php or user.php. Any idea why that would be the case?

    Chris

    • It happens because it is accustomed to add the code below in the theme’s header.php file but since it isn’t really included in majority of the files that’s why the error occurs. I usually advise them to place it in the theme’s index.php right before the get_header() call to make sure it is executed whenever needed.

      if(class_exists('Mage')){
          Mage::getSingleton('core/session', array('name' => 'frontend'));
      }

      I’ll double check as well if there’s any changes in the latest version of WP that could affect the behavior of the default hook I used πŸ™‚

  43. Hi Richard, Everything here works fine, except for the fact that it seems to be pulling the phtml files from the default theme – I am using the modern theme. Any ideas how to change this?

  44. Hi All, Just wondering if anyone has had any success with auto-generating a WordPress user account simultaneously to when a Magento user account is created?

    I have some other variables I need to send to the database when this happens, bit I think if I could any ideas of what others have done, everything will probably start to fall into place πŸ™‚

    Cheers, Wes

    • Hello Wes,

      The trigger must come from Magento since based on your comment, users will be registering thru the shop site instead of WordPress. On the other hand, Mage object within WP can push new accounts to Magento database πŸ™‚

      Regards

  45. Is there a site I can view that has successfully applied the plugin?

    thank you. Looks like this would be great for my existing wp site.

  46. Read all the posts. As a beginning: I have WP on a hosted server, and Magento working on my local machine. Should I install Magento in public html/Shop/? or should I create a subdomain? shop.website.com

    I am not going to use the magento store for purchases so do not need the cart functions. I am using Magento “products” to display service providers and the reviews and ratings functions. I just want to have the wp menus include the magento store pages and not have two home pages. For my purposes I have the wp and magento skins pretty close so ok if different headers and footers for the moment.

    Am I on the right track? Would the below be a good order of procedure?

    1) Create Shop Folder
    2) FTP Magento to Shop Folder.
    3) Create database on server.
    4) Import local machine Magento database
    5) Install mage plugin
    6) follow post and install directions.

    ?
    Thank you.
    Bryan.

  47. Ok, loaded Magento into public html/reviews
    followed the instructions, loaded the plugin, tried using the http://website and then the home/database name/public_html
    and that was accepted and then got this fatal error:

    Fatal error: Uncaught exception ‘PDOException’ with message ‘SQLSTATE[28000] [1045] Access denied for user ‘root’@’localhost’ (using password: NO)’ in /home8/hotlotsa/public_html/Reviews/lib/Zend/Db/Adapter/Pdo/Abstract.php:129 Stack trace: #0 /home8/hotlotsa/public_html/Reviews/lib/Zend/Db/Adapter/Pdo/Abstract.php(129): PDO->__construct(‘mysql:model=mys…’, ‘root’, ”, Array) #1 /home8/hotlotsa/public_html/Reviews/lib/Zend/Db/Adapter/Pdo/Mysql.php(96): Zend_Db_Adapter_Pdo_Abstract->_connect() #2 /home8/hotlotsa/public_html/Reviews/lib/Varien/Db/Adapter/Pdo/Mysql.php(251): Zend_Db_Adapter_Pdo_Mysql->_connect() #3 /home8/hotlotsa/public_html/Reviews/lib/Zend/Db/Adapter/Abstract.php(459): Varien_Db_Adapter_Pdo_Mysql->_connect() #4 /home8/hotlotsa/public_html/Reviews/lib/Zend/Db/Adapter/Pdo/Abstract.php(238): Zend_Db_Adapter_Abstract->query(‘SET NAMES utf8’, Array) #5 /home8/hotlotsa/public_html/Reviews/lib/Varien/Db/Adapter/Pdo/Mysql.php(333): Zend_Db_Adapter_Pdo_Abstract->query(‘SET NAMES utf8’, Array) #6 /home8/hotlotsa/ in /home8/hotlotsa/public_html/Reviews/lib/Zend/Db/Adapter/Pdo/Abstract.php on line 144

    Any suggestions?

  48. Ok; I had not loaded the database yet, so did that and made db name, user and pw, and deleted the var cache, and now the site loads, but a bunch of error codes for the mage php line 676.

    which is:
    —————

    if (is_readable($localConfigFile)) {
    $localConfig = simplexml_load_file($localConfigFile);
    date_default_timezone_set(‘UTC’);
    if (($date = $localConfig->global->install->date) && strtotime($date)) {
    self::$_isInstalled = true;
    }

    ——————
    about 14 errors starting with simplexml_load_file.
    ——————

    Warning: simplexml_load_file() [function.simplexml-load-file]: Entity: line 44: parser error : Opening and ending tag mismatch: username line 44 and bryan1 in /home8/hotlotsa/public_html/Reviews/app/Mage.php on line 676

    Thanks for any help!
    Bryan.

  49. @Tobias, thanks for the clue.

    Here is my local.xml
    I just opened the file from my local machine which works fine, and changed the db name, user name and password to match my server new Magento database, which was a export, import. I did have a database error, though, so may try that process again.

    I can’t find any typo errors?

    false

    1

  50. looks like the comment form is not accepting the code? Trying again, if below is blank how do I post the code?

    false

    1

  51. I appreciate any help, I know this is not really plugin related, but Magento move from local machine to web server, and data base related. Really hoping to see how I can use the integration once I get past these move issues.

    Re: The local.xml file. I moved the local machine local.xml file via ftp, and changed the user, db name, and pw. But not sure if I am doing it correctly. User was [email protected] and tried different versions of my database name: bryan1 and then tried hotlotsa_bryan1.

    I cannot find any screenshots of the way to change it online, most of the tutorials say to load a fresh version of Mangento and the install will create the local.xml file.?

    I also changed the database core_config_data to the correct htttp: for the base and secure url.

    Wondering if i need to deal with the localhost/priveledges of the root user which are set to 127.0.0.1

  52. Now on my main machine I cannot login to WP admin? I get a “page not found” when I try wp_login.php, and normally above the header it sees that I am the admin, and has login links there, which now have gone away.

    On my laptop, can login just fine, and shows the admin info above the header.

    Cookie issue? I rebooted, same, cleared cookies and cache for today, same. Using Firefox on both machines.

    The bright spot is it works and looks great on my laptop!

  53. Ok: got it all working. Shut the machine totally off instead of rebooting, and now the admin page loads. Looking forward to working with the plugin on my site!

  54. I just wanted to say Thank You for the great plugin. I just transferred the database, my Magento public html, plugin, and all, from my WP test server to my main WP site, reset the database and local.xml in 60 minutes, and all is working fine.

    At this point I am happy to “just” have the Magento store pages accessed from my menu, but looking forward to doing some work to match up the headers and footers, and integrate products into posts.

    This is so much better for me than trying to integrate wp into Magento, and not being able to use most of my plugins from WP.
    Very Kewl.

    Bryan.

  55. hi,

    i already pulled magento new products to display in my wordpress.
    but the listing shows 3 columns per row while in my magento it sets 4 columns per row.

    is there a way to set the number of columns to display in my wordpress?

  56. Hi Richard,

    looks like a great WP plugin. Here’s what I’m trying to do with it. We have a main magento store on one domain, and a blog on a seperate domain and machine.

    I’d like to showcase featured products on the blog and don’t need to worry about full integration, simply pass blog visitors to the store and manage them & sales there, at least to begin with.

    I decided to give your plugin a go and installed it but get an invalid url error on the Mage.php when trying to gonfigure the mage enabler – I guess this is because its on a different domain/server/host and related to the path structure input.

    Can you advise if this is do-able (+ correct path structure – using full http:// etc), and if this is the right approach, or do I need to get everything under the same domain/server.?

    I could move the blog over and put it in a sub directory and point the existing blog domain at it I guess.

    Also, for what I’m trying to do intially, is this overkill as a solution..? Is there a simpler way to port featured produtcs into a blog page or category as posts..?

    Having said that, this is something I definitely want to develop further – i.e. the full integration, so the answer to the issues of different domains and machines and paths – if feasible – would be great.

    Thanks for any advice….

  57. Thanks Richard,

    If the blog is in another domain on same server will that work, and if so what will the path look like from the blog domain. e.g. store.com and blog.com on same server, how do I reference mage.php so that the WP install can find it..?

    thanks,

    Iain

  58. Hey there – I got everything working well with my site – the side cart was being updated perfcetly πŸ™‚

    Now all of a sudden the sessions have stopped working. I know that the link to mage.php is still there as pulling blocks out and displaying.

    So my cart is no longer updating. I’ve cleared sessions, used a new browser and checked httpd error/access logs but nothing.

    If anyone has any clues, they would be welcome.

    Many thanks

  59. Pingback: Mage Enabler review, discussions, does it work, and ratings on Loadwp.com | Loadwp.com NETHERLANDS

  60. Hello, I am new to much of this. I am deciding between ahead works and WordPress integration to my Magento store. Is it possible to use your simplified process in a reverse fashion to bring word press into my store.

    • No, not with Mage Enabler. But WordPress itself has a way of extending its functions to external sites. Check on including wp-load.php in your store.

  61. Hey Together,

    i’m trying to get this work. But i’m not getting the correct session. I have an Magento Shop with one Store, Website, View. I just want to view the cart-sidebar. My Code is:

    require_once ( $_SERVER[‘DOCUMENT_ROOT’].”/app/Mage.php” );
    umask(0);
    Mage::app(‘default’);

    Mage::getSingleton(‘core/session’, array(‘name’=>’frontend’));

    $cart = Mage::getSingleton(‘checkout/cart’)->getItemsCount();

    $session = Mage::getSingleton(“customer/session”);

    $block = Mage::getSingleton(‘core/layout’)
    ->createBlock(“checkout/cart_sidebar”, “own_sidebar”)
    ->setTemplate(“checkout/cart/sidebar.phtml”);
    echo $block->toHtml();

    The Cart shows up, but ist empty.

    Would be fine if someone has a solution.

  62. hi, thank you for this wonderful wp plugin, i am following along, but what i came up with were two cookies named “frontend”, one’s path is “/”, and the other one is “/blog”, if in my browser i removed the one whose path is “/blog”, i can see the user logged in, otherwise, it takes it as if i never logged in to the magento site.. has anyone faced this issue?

    thanks.

  63. hi, just to make it clear prior to visiting blog found at http://mysite/blog, i have already logged in at my site as a customer http://mysite. Sometimes the cookie with the path “/blog” doesn’t get created so I can see myself logged in, otherwise most of the time is not letting appear logged in

  64. i think i found out something which i had no clue in magento, setting the cookie path to / so that my blog within my magento site worked, after spending like 6 frustrating hours πŸ™‚

  65. Huge help!

    This helped me to theme out Vanilla forums with my magento header and footer. It was a very similar conflict to the one you mentioned with wordpress… except that there was a conflict with the now() function.

    I simply wrapped the now() function (in app->code->core->mage->core->functions.php) with the if(!function_exists(now){ now()… }

    and it worked like a charm!

    Thanks.

  66. I should amend that last comment. I ended up still having issues, so instead I used the same method of wrapping the function, except this time in the Vanilla Forums version of the “now()” function, instead of in the magento version as I mentioned in my last comment. This function is located in library->core->functions.general.php in the vanilla library

    So far so good, it does not seem to have disabled vanilla forums or messed up the tracking of time in any way.

    I know that is not what this blog post is about, but I figured if anyone finds their way here through google because I mentioned ‘vanilla forum’ and installing magento themes in it, they would appreciate the help πŸ˜‰ The same principles apply to both.

  67. Pingback: Mage Enabler | Best Plugins - wordpress – widgets – plugin 2012

  68. Hello, i tried your suggestions here on http://mysillypointofview.richardferaro.com/2010/04/08/how-to-use-magentos-session-within-wordpress/ and also i tried it with mage enabler plugin , but my site doesn’t fetch the user credentials from magento site, although its running session nicely, but it only show welcome guest , i think i am not getting this line We assumed here that both Magento and WordPress has the same list of user credentials. Your setup maybe different as to which user’s database to use so it’s up to you how to implement it.

    So what i am asking you to please guide me about that? wordpress access with username and password where as magento frontend customers are sharing by mail & password, i won’t to give single login for them.

    thanks.

  69. Hello, i am trying to include Mage into a php file. Checking your example, i’ve included in the php file:

    require_once(‘app/Mage.php’);
    Mage::app();

    $session = Mage::getSingleton(“customer/session”);
    $magento_message = “Welcome “;
    // Generate a personalize greeting
    if($session->isLoggedIn()){
    $magento_message .= $session->getCustomer()->getId();
    }else{
    $magento_message .= “Guest!”;
    }
    echo $magento_message;

    But it does not work, it says Welcome Guest!, insted of Welcome 5 (5 is the customer id i have now, as i am logged in).

    If i paste the previous code on the html file, it works perfectly. How can i integrate Mage correctly in php? Thank you.