How to use Magento’s session within WordPress

120 Comments

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 <richardferaro@gmail.com>
 * @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.

120 Comments (+add yours?)

  1. vesvello
    Apr 09, 2010 @ 09:16:03

    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

    Reply

    • Richard Feraro
      Apr 09, 2010 @ 14:34:09

      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();

      Reply

      • Stephen
        Apr 11, 2010 @ 00:34:13

        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

        Reply

        • Richard Feraro
          Apr 11, 2010 @ 05:37:36

          Hello Stephen,

          It’s in the comments area. Check out the codes I posted right after vesvello’s question.

      • Stephen
        Apr 11, 2010 @ 00:50:11

        Just saw the other comments after my page refreshed. I’ll explore based on your other examples.

        Thanks!

        Reply

  2. Ben Lessani
    Apr 09, 2010 @ 23:59:25

    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!

    Reply

  3. vesvello
    Apr 10, 2010 @ 10:10:25

    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

    Reply

  4. MIchael Bower
    Apr 13, 2010 @ 23:29:36

    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

    Reply

    • Richard Feraro
      Apr 13, 2010 @ 23:43:41

      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

      Reply

  5. zhaojc
    Apr 15, 2010 @ 17:59:02

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

    Reply

    • Richard Feraro
      Apr 15, 2010 @ 20:25:23

      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

      Reply

  6. zhaojc
    Apr 16, 2010 @ 15:06:09

    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

    Reply

    • Richard Feraro
      Apr 16, 2010 @ 15:53:11

      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

      Reply

  7. Peaker
    Apr 16, 2010 @ 22:45:03

    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.

    Reply

    • Richard Feraro
      Apr 17, 2010 @ 05:52:25

      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

      Reply

      • Peaker
        Apr 20, 2010 @ 01:30:17

        Thanks for the reply Richard! I will give it a shot.

        Reply

  8. peaker
    Apr 20, 2010 @ 04:47:42

    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?

    Reply

    • peaker
      Apr 20, 2010 @ 06:40:07

      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 -->

      Reply

      • Richard Feraro
        Apr 20, 2010 @ 10:49:59

        That’s great, peaker!

        Glad that my script helped you get started figuring out on your own how to customize your WP with Magento session running in it.

        Thanks for the feedback :)

        Reply

      • Mark
        Jul 13, 2010 @ 06:32:52

        Can you post this code again using the code tag?

        Reply

        • Richard Feraro
          Jul 13, 2010 @ 15:25:03

          I updated the code to be more readable. :)

  9. James
    Apr 23, 2010 @ 23:25:05

    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

    Reply

    • Richard Feraro
      Apr 23, 2010 @ 23:32:47

      Hi James,

      Try adding $this:

      <?php $this->getChildHtml(‘topSearch’); ?>

      Thanks :)

      Reply

      • James
        Apr 24, 2010 @ 00:01:10

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

        Reply

        • Richard Feraro
          Apr 26, 2010 @ 17:25:22

          Hello James!

          Try using an ‘echo’ also, someone used it here as well.

          Let me know the result :)

      • Brady
        Jun 24, 2010 @ 05:43:26

        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') ?>
        

        Reply

  10. Chris
    Apr 24, 2010 @ 04:34:04

    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?

    Reply

    • Richard Feraro
      Apr 26, 2010 @ 17:42:04

      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.

      Reply

  11. Chris
    Apr 24, 2010 @ 14:12:44

    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?

    Reply

  12. James
    Apr 26, 2010 @ 07:32:31

    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?

    Reply

    • James
      Apr 26, 2010 @ 07:34:51

      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?

      Reply

      • Richard Feraro
        Apr 26, 2010 @ 17:30:45

        Check this out. This is how is display source code in my post and comments.

        Reply

    • Richard Feraro
      Apr 26, 2010 @ 18:10:08

      It seems your script should work now but I can’t see your whole script. Also try checking this post so you can validate also if you accidentally missed something.

      Reply

      • James
        Apr 28, 2010 @ 23:05:11

        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>
        

        Reply

        • Richard Feraro
          Apr 28, 2010 @ 23:18:10

          Is this your code in your .phtml file for header?

        • James
          Apr 29, 2010 @ 00:41:32

          yes thats right Richard ( its obviously been customised from the base file )

        • Richard Feraro
          Apr 29, 2010 @ 17:46:35

          It looks fine to me. What happens when your try to run your script?

        • James
          Jun 24, 2010 @ 06:48:31

          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 ;-)

        • Richard Feraro
          Jun 24, 2010 @ 16:19:27

          Hmm, are you using Mage Enabler plugin or the previous hack I did in functions.php?

        • James
          Jun 24, 2010 @ 06:52:56

          Since the project went on hold, this was never completed – but to answer your question:
          nothing happens – nothing is displayed and no errors either.

        • Richard Feraro
          Jun 24, 2010 @ 16:21:41

          If nothing happened and the page went blank (white), it means there’s a fatal error in your code. Use error_reporting(E_ALL) at the top of the script you’re working on to display the error.

  13. Chris
    Apr 26, 2010 @ 19:54:54

    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?

    Reply

  14. Chris
    Apr 26, 2010 @ 21:23:03

    I get it to work on version 1.4.0.0 strangely enough.

    Reply

  15. Chris
    Apr 27, 2010 @ 03:42:17

    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.

    Reply

    • Richard Feraro
      Apr 27, 2010 @ 13:50:05

      Well looks like your problem is actually your browser cache.

      Reply

  16. Chris
    Apr 27, 2010 @ 18:56:02

    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!

    Reply

    • Richard Feraro
      Apr 27, 2010 @ 19:25:11

      Great! Good thing you found a fix for that one. :)

      Reply

    • Brady
      Jun 23, 2010 @ 09:14:51

      I was experiencing the same errors as you were. Thanks for your tip on the Store Names in Magento. We also run a multi-store setup, so we changed the default name. I simply entered our custom name into the WordPress functions.php and it worked like a charm!

      Reply

  17. peaker
    Apr 28, 2010 @ 01:36:35

    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?

    Reply

    • Richard Feraro
      Apr 28, 2010 @ 01:49:35

      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.

      Reply

  18. peaker
    Apr 28, 2010 @ 02:20:24

    Good point. Thanks Richard.

    Reply

  19. erica
    Apr 30, 2010 @ 05:47:21

    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.

    Reply

    • Richard Feraro
      Apr 30, 2010 @ 10:22:54

      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?

      Reply

  20. erica
    Apr 30, 2010 @ 19:15:42

    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.

    Reply

    • Richard Feraro
      Apr 30, 2010 @ 20:04:48

      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 :)

      Reply

  21. bretjg
    May 01, 2010 @ 01:19:11

    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

    Reply

    • Richard Feraro
      May 01, 2010 @ 11:10:49

      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!

      Reply

  22. Kiper IT-konsult
    May 05, 2010 @ 13:20:44

    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!

    Reply

    • Richard Feraro
      May 05, 2010 @ 15:06:37

      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 :)

      Reply

  23. Olivier
    May 06, 2010 @ 00:07:42

    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.

    Reply

    • Richard Feraro
      May 06, 2010 @ 02:34:55

      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 :)

      Reply

  24. Olivier
    May 06, 2010 @ 03:59:12

    Sounds good :)
    Let me know if you need any help with the plugin, would be a pleasure.

    Reply

  25. timani
    May 14, 2010 @ 11:18:13

    In a word excellent! Definitely more transparent + documented + supported than lazymonks in my opinion

    Reply

  26. Greg Lutz
    May 26, 2010 @ 16:46:09

    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

    Reply

    • Greg Lutz
      May 26, 2010 @ 18:24:27

      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

      Reply

      • Richard Feraro
        May 26, 2010 @ 18:32:46

        Oh I see. Is it the functions.php the file where you added the code above? Restore it again to its original and use the Mage Enabler plugin from the Official WordPress Plugin repo then let me know how it goes.

        Reply

    • Richard Feraro
      May 26, 2010 @ 18:47:23

      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.

      Reply

  27. Greg Lutz
    May 26, 2010 @ 19:48:29

    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.

    Reply

    • Richard Feraro
      May 26, 2010 @ 19:53:54

      Check the folder structure. It should be similar to the setup below:

      Reply

      • Greg Lutz
        May 26, 2010 @ 20:03:49

        Here’s the set-up:
        root: /html/blog/wp-content/plugins/mage-enabler/mage-enabler

        with the correct images and files.

        Reply

        • Richard Feraro
          May 26, 2010 @ 20:12:01

          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

        • Greg Lutz
          May 26, 2010 @ 20:25:00

          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

        • Richard Feraro
          May 26, 2010 @ 20:43:34

          Follow the instructions in this post

        • Richard Feraro
          Jun 10, 2010 @ 21:01:05

          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’ :)

  28. Jim
    Jun 02, 2010 @ 19:04:41

    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

    Reply

    • Richard Feraro
      Jun 02, 2010 @ 21:45:33

      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 :)

      Reply

      • Jim
        Jun 09, 2010 @ 22:27:27

        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!

        Reply

        • Richard Feraro
          Jun 10, 2010 @ 01:05:02

          Yep! Thanks too. Keep on reading :)

  29. BJ Johnson
    Jun 13, 2010 @ 07:59:19

    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.

    Reply

    • Richard Feraro
      Jun 13, 2010 @ 14:48:00

      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.

      Reply

  30. BJ Johnson
    Jun 13, 2010 @ 11:02:02

    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.

    Reply

    • Richard Feraro
      Jun 13, 2010 @ 15:03:16

      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.

      Reply

  31. BJ Johnson
    Jun 13, 2010 @ 16:06:17

    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.

    Reply

    • Richard Feraro
      Jun 13, 2010 @ 16:51:57

      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.

      Reply

  32. James
    Jun 23, 2010 @ 23:21:00

    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

    Reply

    • Richard Feraro
      Jun 24, 2010 @ 01:59:31

      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 :)

      Reply

  33. James
    Jun 24, 2010 @ 06:50:40

    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 ;-)

    Reply

  34. James
    Jun 24, 2010 @ 07:06:07

    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
    

    Reply

    • James
      Jun 24, 2010 @ 23:29:23

      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! )

      Reply

      • Richard Feraro
        Jun 25, 2010 @ 02:17:27

        Is it possible to see the whole file where you’re using this script? I can’t figure out how you came up with $magento_block and what causes your error.

        Reply

        • James
          Jun 30, 2010 @ 18:02:03

          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

        • Richard Feraro
          Jul 01, 2010 @ 01:48:52

          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.

        • Brady
          Jul 01, 2010 @ 06:31:31

          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
          

        • Richard Feraro
          Jul 01, 2010 @ 11:52:14

          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>

        • Richard Feraro
          Jul 03, 2010 @ 00:11:44

          Check out my latest post regarding this one.

  35. Brady
    Jun 25, 2010 @ 02:57:39

    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’) ?>

    Reply

    • Richard Feraro
      Jun 25, 2010 @ 21:04:42

      One of the commenters here (peaker) were able to extract Magento blocks.
      Check this thread which he used to solve his problem with blocks: http://www.magentocommerce.com/boards/viewthread/17459/#t60477

      Reply

      • Brady
        Jun 29, 2010 @ 05:49:30

        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);
                }
            }
        

        Reply

        • Richard Feraro
          Jun 29, 2010 @ 15:21:09

          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?

        • Brady
          Jun 30, 2010 @ 02:44:49

          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.

        • Richard Feraro
          Jul 01, 2010 @ 01:53:11

          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 :)

      • Brady
        Jun 29, 2010 @ 05:50:41

        When I do a PHP include to the entire abstract.php file, the screen goes white.

        Reply

        • Richard Feraro
          Jun 29, 2010 @ 15:22:19

          You shouldn’t include that file.

  36. Brady
    Jul 02, 2010 @ 07:09:19

    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 .

    Reply

  37. Brady
    Jul 02, 2010 @ 09:41:27

    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() ?>

    Reply

  38. Darrell
    Jul 23, 2010 @ 00:30:47

    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.

    Reply

    • Richard Feraro
      Jul 23, 2010 @ 04:20:57

      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?

      Reply

Leave a Reply