How to add Magento blocks, CSS and Javascript to an external site
Jul 03
Feeling guru Magento, php, programming 25 Comments
You might have a Magento based website running online and wanted to extend parts of it (also known as blocks, which may include some css and js in the code) to an external site which may either be a blog, another CMS or any other PHP based web application. If you have been following my previous posts, you will know that by adding the Mage.php file of your Magento instance to your application, you can actually pull the needed HTML blocks at any time. The only problem is that most of the examples available online asks you to use the getChildHtml(‘your-block-here’) in which most the time frustrates you because of its complexity and limited resources of how you can actually use it.
There are other ways of doing it. Oddly enough, some are pretty simple and straight forward.
We will use a single HTML file which will serve as our ‘external’ site. The source code of our index.php is shown below:
<html>
<head>
<script type="text/javascript">
WebFontConfig = {
google: { families: [ 'Josefin Sans Std Light', 'Lobster' ] }
};
(function() {
var wf = document.createElement('script');
wf.src = ('https:' == document.location.protocol ? 'https' : 'http') +
'://ajax.googleapis.com/ajax/libs/webfont/1/webfont.js';
wf.type = 'text/javascript';
wf.async = 'true';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(wf, s);
})();
</script>
<style type="text/css">
.wf-active p.text {
font-family: 'Calibri', serif;
font-size: 16px;
text-align: justify;
color:#666666;
border: 1px solid #CCCCCC;
-moz-border-radius: 20px;
-webkit-border-radius: 20px;
padding: 20px
}
.wf-active h2 {
font-family: 'Lobster', serif;
font-size: 20px;
color: #666666
}
.wf-active h1 {
font-family: 'Lobster', serif;
font-size: 45px;
color: #006699;
margin-bottom: 10px;
}
div.body {
max-width: 850px;
margin: auto;
background-color: #FFFFFF;
padding: 30px 50px 0px 50px;
text-align: left;
height: 60%;
}
p.bugs {
font: 12px/1.55 Arial,Helvetica,sans-serif;
text-align: center;
}
p.otherdata {
font-family: 'Calibri', serif;
font-size: 15px;
color: #999999;
margin-bottom: 20px
}
.otherdata strong {
color: #000000
}
</style>
</head>
<body>
<div class="body">
<h1>How to add Magento blocks, CSS and Javascript to an external site</h1>
<p class="otherdata">Written by <strong>Richard Feraro</strong> | Posted on <strong>July 2, 2010</strong></p>
<p class="text">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis a quam massa. Nullam eget erat metus. Sed vel justo enim. Proin rhoncus laoreet bibendum. Nullam eget est nisi. In eget sem in erat sodales bibendum. Morbi gravida augue sed felis tincidunt a congue dui placerat. Aliquam purus risus, mollis sed ullamcorper non, viverra eu odio. Suspendisse nibh nisi, suscipit at viverra eu, convallis ac odio. Morbi nec sapien eros. Suspendisse nec nulla erat, ac porttitor neque. Integer felis dolor, sollicitudin sed semper et, imperdiet nec turpis. Proin blandit luctus egestas. </p>
</div>
</body>
</html>
The code above shall produce a page like the one in the screenshot below.
We’ll start editing at the beginning of the file by adding a require_once() for our Mage.php file.
// Your Magento Mage.php
// Mage Enabler WordPress plugin users may
// skip these lines
require_once ("/your/magento/app/Mage.php");
umask(0);
Mage::app("default");
Proceed with adding the if(class_exists('Mage')){...} which encloses our Magento scripts to prevent the site from breaking if in case the Mage object failed to be instantiated. Check the inline comments for more details.
// Make sure to execute this block of code
// only if Mage object is present
if(class_exists('Mage')){
// Instantiate session and generate needed cookie
Mage::getSingleton('core/session', array('name' => 'frontend'));
$Block = Mage::getSingleton('core/layout');
// Start pulling the blocks
$head = $Block->createBlock('Page/Html_Head');
// Add default css
// Magento adds the default skin directory
// 'skin/frontend/default/default' before 'css/styles.css'
// making it look like the URL below:
// http://localhost/magento/skin/frontend/default/default/css/styles.css
$head->addCss('css/styles.css');
// Add Prototype JS file
// Note that it automatically adds the 'js' directory at the beginning
// making it look like the URL below:
// http://localhost/magento/js/prototype/prototype.js
$head->addJs('prototype/prototype.js');
// Get the header's HTML
$header = $Block->createBlock('Page/Html_Header');
$header->setTemplate('page/html/header.phtml');
// And the footer's HTML as well
$footer = $Block->createBlock('Page/Html_Footer');
$footer->setTemplate('page/html/footer.phtml');
}
That’s it. The codes above will generate the Magento session, the 3 blocks for CSS/JS (which uses the default skin of Magento and adds the Prototype JS file) and the HTML tags for the header and footer.
To use the blocks, insert the CSS/JS block right before the end tag of </HEAD>:
<?php
// Display the needed tags for CSS and JS
echo (class_exists('Mage')) ? $head->getCssJsHtml() : '' ;
?>
</head>
Proceed by adding the Magento header block right after the <BODY> tag but before the <DIV> tag.
<body>
<?php
// Display the Header HTML
echo (class_exists('Mage')) ? $header->toHTML() : '' ;
?>
<div class="body">
Finally, add the Magento footer block right between the end tag of </DIV> and </BODY> tag
</div>
<?php
// Display the Footer HTML
echo (class_exists('Mage')) ? $footer->toHTML() : '' ;
?>
</body>
It should display a page of our external site which now uses the header and footer of Magento. Check the source to see the additional tags generated.
The full index.php can be found below:
<?php
// Your Magento Mage.php
// Mage Enabler WordPress plugin users may
// skip line numbers 5, 6 and 7
require_once ("/your/magento/app/Mage.php");
umask(0);
Mage::app("default");
// Make sure to execute this block of code
// only if Mage object is present
if(class_exists('Mage')){
// Instantiate session and generate needed cookie
Mage::getSingleton('core/session', array('name' => 'frontend'));
$Block = Mage::getSingleton('core/layout');
// Start pulling the blocks
$head = $Block->createBlock('Page/Html_Head');
// Add default css
// Magento adds the default skin directory
// 'skin/frontend/default/default' before 'css/styles.css'
// making it look like the URL below:
// http://localhost/magento/skin/frontend/default/default/css/styles.css
$head->addCss('css/styles.css');
// Add Prototype JS file
// Note that it automatically adds the 'js' directory at the beginning
// making it look like the URL below:
// http://localhost/magento/js/prototype/prototype.js
$head->addJs('prototype/prototype.js');
// Get the header's HTML
$header = $Block->createBlock('Page/Html_Header');
$header->setTemplate('page/html/header.phtml');
// And the footer's HTML as well
$footer = $Block->createBlock('Page/Html_Footer');
$footer->setTemplate('page/html/footer.phtml');
}
?>
<html>
<head>
<script type="text/javascript">
WebFontConfig = {
google: { families: [ 'Josefin Sans Std Light', 'Lobster' ] }
};
(function() {
var wf = document.createElement('script');
wf.src = ('https:' == document.location.protocol ? 'https' : 'http') +
'://ajax.googleapis.com/ajax/libs/webfont/1/webfont.js';
wf.type = 'text/javascript';
wf.async = 'true';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(wf, s);
})();
</script>
<style type="text/css">
.wf-active p.text {
font-family: 'Calibri', serif;
font-size: 16px;
text-align: justify;
color:#666666;
border: 1px solid #CCCCCC;
-moz-border-radius: 20px;
-webkit-border-radius: 20px;
padding: 20px
}
.wf-active h2 {
font-family: 'Lobster', serif;
font-size: 20px;
color: #666666
}
.wf-active h1 {
font-family: 'Lobster', serif;
font-size: 45px;
color: #006699;
margin-bottom: 10px;
}
div.body {
max-width: 850px;
margin: auto;
background-color: #FFFFFF;
padding: 30px 50px 0px 50px;
text-align: left;
height: 60%;
}
p.bugs {
font: 12px/1.55 Arial,Helvetica,sans-serif;
text-align: center;
}
p.otherdata {
font-family: 'Calibri', serif;
font-size: 15px;
color: #999999;
margin-bottom: 20px
}
.otherdata strong {
color: #000000
}
</style>
<?php
// Display the needed tags for CSS and JS
echo (class_exists('Mage')) ? $head->getCssJsHtml() : '' ;
?>
</head>
<body>
<?php
// Display the Header HTML
echo (class_exists('Mage')) ? $header->toHTML() : '' ;
?>
<div class="body">
<h1>How to add Magento blocks, CSS and Javascript to an external site</h1>
<p class="otherdata">Written by <strong>Richard Feraro</strong> | Posted on <strong>July 2, 2010</strong></p>
<p class="text">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis a quam massa. Nullam eget erat metus. Sed vel justo enim. Proin rhoncus laoreet bibendum. Nullam eget est nisi. In eget sem in erat sodales bibendum. Morbi gravida augue sed felis tincidunt a congue dui placerat. Aliquam purus risus, mollis sed ullamcorper non, viverra eu odio. Suspendisse nibh nisi, suscipit at viverra eu, convallis ac odio. Morbi nec sapien eros. Suspendisse nec nulla erat, ac porttitor neque. Integer felis dolor, sollicitudin sed semper et, imperdiet nec turpis. Proin blandit luctus egestas. </p>
</div>
<?php
// Display the Footer HTML
echo (class_exists('Mage')) ? $footer->toHTML() : '' ;
?>
</body>
</html>
RSS
Facebook
Friendster
LinkedIn
Follow me on Twitter

Jul 03, 2010 @ 04:53:06
Hey – first off – thanks for all your work on this and your help via twitter. I’m trying to plug this into the basic twenty-ten theme for WordPress – As soon as it hits the code:
toHTML() : ” ;
?>
It dies. Any ideas on what I’m doing wrong?
http://biffy.tinyfac.com is where it’s testing at
Much thanks in advance.
Jul 03, 2010 @ 12:03:51
Hello Michael, you’re welcome.
I see that it’s blank which means there’s a fatal error somewhere within your code. Place error_reporting(E_ALL) (no quotes) at the very top of the file you’re working on to see the actual error.
Jul 03, 2010 @ 04:54:04
Sorry –
toHTML() : '' ;
?>
Jul 03, 2010 @ 12:06:41
It’s a short style IF condition. You should complete the syntax:
(your_condition_here) ? value_if_true : value_if_false;echo (class_exists('Mage')) ? $header->toHTML() : '' ;Jul 03, 2010 @ 12:09:56
You can also post code here using the following format:
[php] your code here [/php]
Jul 06, 2010 @ 09:50:53
Hi Richard,
Thanks so much for this addition to your series. It definitely simplifies things for what I’m trying to do and I ALMOST have it working now.
When I plug in this code, it pulls in everything, except the CSS. Because it’s trying to pull in the default/default/css/styles.css, which doesn’t exist. Is there a way to point this to the current skin, instead of the default skin?
When I create a styles.css and try to pull in all my themed CSS files using @import in the default/css/styles.css, it doesn’t import them for some reason.
Thanks again!
Jul 06, 2010 @ 12:16:03
Is your store configured to use the skin that you want? I’ll try to install a different skin to see if it does pull what is currently configured in the admin.
Jul 06, 2010 @ 16:39:40
Hi Brady, yes it pulls the theme’s file currently configured for the store found in the admin. See theme creation details here.
Either you just copied the whole theme files from the default provided or you haven’t set the store to use the custom theme you made in the admin page.
It is configured in your custom theme’s local.xml and/or page.xml file to call the action method “addCss”. Check this link and also this one.
Don’t forget to clear or disable Magento’s cache in the administration panel right after you make any changes to your files.
Jul 09, 2010 @ 05:46:07
Hey – so thanks to your help I’ve got the basic working. Now most of my header is made up of echo $this->getChildHtml calls from w/ in the header. They’re not printing anything at the moment – what I can do to pull in these getChildHtml calls as well as the main header?
So my header code is:
<a name="top"></a> <div class="header"> <h1 id="logo"><a href="<?php echo $this->getUrl('') ?>"><img src="<?php echo $this->getLogoSrc() ?>" alt="<?php echo $this->getLogoAlt() ?>"/></a></h1> <?php echo $this->getChildHtml('store_language') ?> <img class="promo" src="<?php echo $this->getSkinUrl('images/freeshipping.png') ?>" alt="<?php echo $this->__('Free Shipping') ?>"/> <div class="mainLinks"> <div class="headerLinks"> <?php echo $this->getLayout()->createBlock('cms/block')->setBlockId('headerlinks')->toHtml() ?> </div> <div class="clear"></div> <div class="toplinks"> <?php echo $this->getChildHtml('topLinks') ?> </div> </div> <div class="clear"></div> </div> <div id="navigation"> <?php echo $this->getChildHtml('topMenu') ?> </div> <div class="clear"></div>but it’s printing:
<a name="top"></a> <div class="header"> <h1 id="logo"><a href="http://biffy.tinyfac.com/home/cart/index.php/"><img src="http://biffy.tinyfac.com/home/cart/skin/frontend/default/hellouno/images/logo.gif" alt="Magento Commerce"/></a></h1> <img class="promo" src="http://biffy.tinyfac.com/home/cart/skin/frontend/default/hellouno/images/freeshipping.png" alt="Free Shipping"/> <div class="mainLinks"> <div class="headerLinks"> <li class="first"><a href="#">Store Locator</a></li> <li><a href="#">Privacy Policy</a></li> <li><a href="#">Support Policy</a></li> <li><a href="#">Customer Service</a></li> <li><a href="#">FAQs</a></li> <li class="last"><a href="#">Contact Us</a></li> </div> <div class="clear"></div> <div class="toplinks"> </div> </div> <div class="clear"></div> </div> <div id="navigation"> </div> <div class="clear"></div>any advice is much appreciated!
Jul 09, 2010 @ 15:59:48
Thanks
Someone named peaker was able to do it from the other post. Read his comments here.
Jul 10, 2010 @ 09:01:46
Hi Richard,
I’m following your tutorial above using it on a fresh local install of the latest Magento and WordPress. So far everything looks pretty smooth, except I can’t get the JavaScript to import in the Head. I use your
$head->addJs('prototype/prototype.js');, similar to how the CSS is brought in. The CSS imports fine, but the JavaScript doesn’t show up anywhere.
Any ideas?
Jul 10, 2010 @ 09:05:15
Actually, I take that back. The one prototype/prototype.js gets pulled in, but none of my other JavaScript does.
Here’s what I’m using:
Jul 10, 2010 @ 14:02:49
You have to create an action method ‘addJs’ for each JS file that you want to add in your local.xml/page.xml found in your custom theme folder. Refer to this article from Magento.
Jul 13, 2010 @ 09:15:54
Hi Richard,
Sorry for all the confusion on my end. I read the article you referred to about creating the local.xml file to add the additional JS files.
My question is – those files are already added in the default page.xml. Do I need to re-add them in a local.xml file anyway?
page.xml:
<block type="page/html_head" name="head" as="head"> <action method="addJs"><script>prototype/prototype.js</script></action> <action method="addJs"><script>lib/ccard.js</script></action> <action method="addJs" ifconfig="dev/js/deprecation"><script>prototype/deprecation.js</script></action> <action method="addJs"><script>prototype/validation.js</script></action> <action method="addJs"><script>scriptaculous/builder.js</script></action> <action method="addJs"><script>scriptaculous/effects.js</script></action> <action method="addJs"><script>scriptaculous/dragdrop.js</script></action> <action method="addJs"><script>scriptaculous/controls.js</script></action> <action method="addJs"><script>scriptaculous/slider.js</script></action> <action method="addJs"><script>varien/js.js</script></action> <action method="addJs"><script>varien/form.js</script></action> <action method="addJs"><script>varien/menu.js</script></action> <action method="addJs"><script>mage/translate.js</script></action> <action method="addJs"><script>mage/cookies.js</script></action> <action method="addCss"><stylesheet>css/reset.css</stylesheet></action> <action method="addCss"><stylesheet>css/boxes.css</stylesheet></action> <action method="addCss"><stylesheet>css/menu.css</stylesheet></action> <action method="addCss"><stylesheet>css/clears.css</stylesheet></action> <action method="addCss"><stylesheet>css/styles.css</stylesheet></action> <action method="addItem"><type>skin_css</type><name>css/iestyles.css</name><params/><if>lt IE 8</if></action> <action method="addItem"><type>skin_css</type><name>css/ie7minus.css</name><params/><if>lt IE 7</if></action> <action method="addItem"><type>js</type><name>lib/ds-sleight.js</name><params/><if>lt IE 7</if></action> <action method="addItem"><type>js</type><name>varien/iehover-fix.js</name><params/><if>lt IE 7</if></action> <action method="addCss"><stylesheet>css/print.css</stylesheet><params>media="print"</params></action> </block>Jul 13, 2010 @ 16:05:28
I was able to add the same files you listed in your code using the same example in the article:
$head->addCss('css/reset.css'); $head->addCss('css/boxes.css'); $head->addCss('css/menu.css'); $head->addCss('css/clears.css'); $head->addCss('css/styles.css'); $head->addCss('css/print.css.css'); // Add Prototype JS file // Note that it automatically adds the 'js' directory at the beginning // making it look like the URL below: // http://localhost/magento/js/prototype/prototype.js $head->addJs('prototype/prototype.js'); $head->addJs('prototype/validation.js'); // This js file automatically adds the scriptaculous related js files $head->addJs('scriptaculous/scriptaculous.js'); // Mage related js $head->addJs('varien/js.js'); $head->addJs('varien/form.js'); $head->addJs('varien/menu.js'); $head->addJs('mage/translate.js'); $head->addJs('mage/cookies.js');Maybe its because of these two lines (check my inline comments):
// Is this file existing in your magento-root/js folder? $head->addJs('lib/ccard.js'); // I'm sure this is a typo. It should be $head->addJs('prototype/validation.js'); $head->addJs('protype/validatio.js');Jul 13, 2010 @ 16:18:58
Also, there’s only page.xml file in my magento default theme directory, no local.xml. I didn’t change any XML file too.
Jul 14, 2010 @ 03:18:02
Hi Richard,
Thanks so much for the help, as always.
This was totally something I overlooked. When I look the source code of my dev site, I only saw one line of JS. But when I look at that JS it contains all the “addJs” files. I wasn’t aware that Magento combines the JS files.
Still working on pulling in the ‘getChildHtml’ references…
Jul 14, 2010 @ 05:49:40
Hi Richard,
Okay, I’m getting the hang od the getChildHtml replacement, but how do I nest blocks?
In your example above, it pulls in the header just fine, but leaves out the top links, navigation and search box. I’m able to pull in all those items separately, but how do I tell them to go into the header? I read on the forums about using ‘setParentBlock’ but that’s undefined when I try to access it from WordPress.
I’m defining the the navigation using:
// Get Navigation $topMenu = $Block->createBlock('Catalog/Navigation'); $topMenu->setTemplate('catalog/navigation/top.phtml');and displaying it using:
echo (class_exists('Mage')) ? $topMenu->toHTML() : '' ;Jul 14, 2010 @ 07:39:38
This is what I am looking for.
@Brady How did you pull the items separately? What code are you using?
@Richard I understand you are busy but I think it would be a good idea to add a skeleton theme to the plugin that has all the header info and footer in it. Or a stand alone theme, eighter way the user would have the option to activate the theme, right? This might not work for everyone because not every magento theme is the same. Or maybe it will, not sure.
Thanks,
Mark
Jul 14, 2010 @ 07:41:55
Sorry.
typo->either
Jul 14, 2010 @ 13:33:01
Hi Mark,
Here’s my WordPress Theme index.php file so far (sorry for the long post, Richard):
<?php // Your Magento Mage.php // Mage Enabler WordPress plugin users may skip line numbers 5, 6 and 7 // require_once ("/your/magento/app/Mage.php"); */ // umask(0); */ // Mage::app("default"); */ // Make sure to execute this block of code only if Mage object is present if(class_exists('Mage')){ // Instantiate session and generate needed cookie Mage::getSingleton('core/session', array('name' => 'frontend')); $Block = Mage::getSingleton('core/layout'); // Start pulling the blocks $head = $Block->createBlock('Page/Html_Head'); // Add default css // Magento adds the default skin directory 'skin/frontend/default/default' before 'css/styles.css' making it look like the URL below: // http://localhost/magento/skin/frontend/default/default/css/styles.css $head->addCss('css/reset.css'); $head->addCss('css/boxes.css'); $head->addCss('css/menu.css'); $head->addCss('css/clears.css'); $head->addCss('css/styles.css'); $head->addCssIe('css/styles.css'); $head->addCssIe('css/styles.css'); $head->addCss('css/print.css.css'); // Add Prototype JS file // Note that it automatically adds the 'js' directory at the beginning making it look like the URL below: // http://localhost/magento/js/prototype/prototype.js $head->addJs('prototype/prototype.js'); $head->addJs('lib/ccard.js'); $head->addJs('protype/validation.js'); $head->addJs('scriptaculous/builder.js'); $head->addJs('scriptaculous/effects.js'); $head->addJs('scriptaculous/dragdrop.js'); $head->addJs('scriptaculous/controls.js'); $head->addJs('scriptaculous/slider.js'); $head->addJs('varien/js.js'); $head->addJs('varien/form.js'); $head->addJs('varien/menu.js'); $head->addJs('mage/translate.js'); $head->addJsIE('css/styles.css'); $head->addJs('mage/cookies.js'); // Get the header's HTML $header = $Block->createBlock('Page/Html_Header'); $header->setTemplate('page/html/header.phtml'); /* $header = $Block->createBlock('page/html/header.phtml'); */ // Get Top Search HTML $topSearch = $Block->createBlock('Core/Template'); $topSearch->setTemplate('catalogsearch/form.mini.phtml'); /* $topSearch = $Block->createBlock('catalogsearch/form.mini.phtml'); */ /* $topSearch->setParentBlock($header); */ // Get Navigation $topMenu = $Block->createBlock('Catalog/Navigation'); $topMenu->setTemplate('catalog/navigation/top.phtml'); // And the footer's HTML as well $footer = $Block->createBlock('Page/Html_Footer'); $footer->setTemplate('page/html/footer.phtml'); } ?> <html> <head> <?php // Display the needed tags for CSS and JS echo (class_exists('Mage')) ? $head->getCssJsHtml() : '' ; ?> </head> <body> <?php // Display the Header HTML echo (class_exists('Mage')) ? $topSearch->toHTML() : '' ; echo (class_exists('Mage')) ? $header->toHTML() : '' ; echo (class_exists('Mage')) ? $topMenu->toHTML() : '' ; ?> <div id="container"> <div id="content" role="main"> <?php /* Run the loop to output the posts. * If you want to overload this in a child theme then include a file * called loop-index.php and that will be used instead. */ get_template_part( 'loop', 'index' ); ?> </div><!-- #content --> </div><!-- #container --> <?php get_sidebar(); ?> <?php // Display the Footer HTML echo (class_exists('Mage')) ? $footer->toHTML() : '' ; ?> </body> </html>Jul 14, 2010 @ 22:47:38
Thanks, I will try it out. Sorry for hijacking your comment.
Jul 14, 2010 @ 16:10:09
It’s already posted here.
You already answered that. I’ll just quote what you said, “This might not work for everyone because not every magento theme is the same.”
If you have read every Magento-related post I have here, you will see that I’m not really discussing any theme-related modification here. What I post here is how to use Magento’s session to an external site. That external site could be a forum, a blogging tool or any PHP based web application that’s why there’s no need to create any “skeleton theme” like you mentioned. Magento session, in its simplest definition is actually a PHP object and its up to the reader how he will use and manipulate that object to achieve his task (Magento Documentation).
Please consider also that I’m in Manila, Philippines and we have somewhere between 8 to 12 hour time difference. I may not be able to reply immediately, but I always reply back to every comment/inquiry here.
Aug 18, 2010 @ 08:47:14
HI Richard,
thats what i searched for to build an ajax card! great post!!!
I got only one problem with the locale.
Mage::app()->getLocale()->getLocaleCode(); shows de_DE, thats perfect but that block is in en_EN.
any ideas how to set locale or right locale folder?
Aug 18, 2010 @ 17:13:59
Hello sajo!
You can use setLocaleCode.