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

/**
 * Run Magento's Mage.php within WordPress
 *
 * @author Richard Feraro <richardferaro@gmail.com>
 * @link https://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));
}

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

?>

<?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();
	$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();
	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.