Customising Magento Transactional Emails

As part of a recent project customising Magento emails I discovered a few useful bits and pieces that make creating custom transactional emails a little easier.

Static Blocks

I am not sure why I hadn’t thought of this but you can use static blocks in your emails in the same way as you would a CMS page. This is great because it allows you to make blocks that you can include in every email such as:
– Header
– Footer
– Promotional Content Area
– Social Links
etc and centrally manage it or allow the client to manage it rather than editing every email individually. The code you need is as follows:

{{block type="cms/block" block_id="email-header" template="cms/content.phtml"}}

You can place this code either in the emails you have setup within “system/transactional emails” or within your site directory “app/locale/en-us/template/email/email-file-name.html” with en-us being whatever locale you happen to be using.

Another cool thing about this is that you can easily upload images and include them within the static block admin screen rather than including the images in your theme. This makes it easy for clients to refresh certain sections themselves or write promotional content.

Referencing Store Information

Magento as standard references a few of the fields in the admin to populate the email eg. Store Name. However it is useful to also know that you can reference a lot more of the store information. For example if you are creating an email footer to state the stores name, address, telephone number, vat number etc you can pull all this information in dynamically so that your emails are kept up to date. The code required is:

Copyright: {{config path='design/footer/copyright'}}
Address: {{config path='general/store_information/address'}}
VAT No: {{config path='general/store_information/merchant_vat_number'}}
Telephone Number: {{config path='general/store_information/phone'}}
Email: {{config path='trans_email/ident_support/email'}}

and if you require anything else the easiest way to see how the field would be called is to browse to the section in the admin and inspect the field for its “name”. You would then write the code as follows:

{{config path=’tab in admin/sub section in admin/field name’}}

Sending Mail in Xampp

I have literally spent hours trying to set up mail on my localhost so that I can send test emails from Magento, and finally its working. So I thought I would share my solution in case it saves others wasted hours too 🙂

Firstly I needed to download the most recent release of sendmail. This can be found here: Once downloaded browse to c:/xampp/sendmail (assuming your installation is on your c:/ drive) and delete and replace with the newly downloaded files.

Then in c:/xampp/sendmail/sendmail.ini comment everything out but the following lines and modify to be your own email address and password.

Then in c:/xampp/php/php.ini search for “mail” and comment out everything but sendmail_path and mail.add_x_header lines.

; For Win32 only.
;SMTP = localhost
;smtp_port = 25
; For Win32 only.
;sendmail_from = postmaster@localhost
; For Unix only.  You may supply arguments as well (default: "sendmail -t -i").
sendmail_path = "\"C:\xampp\sendmail\sendmail.exe\" -t"
; Force the addition of the specified parameters to be passed as extra parameters
; to the sendmail binary. These parameters will always replace the value of
; the 5th parameter to mail(), even in safe mode.
;mail.force_extra_parameters =
; Add X-PHP-Originating-Script: that will include uid of the script followed by the filename
mail.add_x_header = Off
; Log all mail() calls including the full path of the script, line #, to address and headers
;mail.log = "C:\xampp\apache\logs\php_mail.log"

Then restart Apache and it should work!!
To test you can place this script in your htdocs change the $to field and browse to it.

$to = "";
$subject = "Test Email";
$message = "Testing mail is working";
echo "sent";
echo "failed";

Thank you to for pointing me in the right direction 🙂

Expanding Left Hand Category Menu in Magento

The below code will create a menu that shows the siblings of an active category as well as showing its grandchildren. This will allow a user to jump between categories easily. Active classes are provided and the parent category is used to create a title. Again I am not a PHP developer so any bug fixes or tips are welcome.

Modify app/design/frontend/YOUR THEME/default/template/catalog/navigation/left.phtml to contain:

<?php $helper = $this->helper('catalog/category') ?>
<?php $categories = $this->getStoreCategories() ?>
<?php $categoriescount = $this->getStoreCategories()->count();?>
<div class="block block-layered-nav">
//If there are any root categories
if ($categoriescount > 0): 
	foreach($categories as $category): 
		//Get sub categories 
		$subcategories = $category->getChildren();
		//Number of sub categories
		$subcategoriescount = $category->getChildren()->count(); 
		// Display active root category as block title only if there are sub categories
		if ($this->isCategoryActive($category) && $subcategoriescount > 0): 
		<div class="block-title">
		<a href="<?php echo $helper->getCategoryUrl($category) ?>">
			<strong><span><?php echo $this->escapeHtml($category->getName()) ?></span></strong>
		<div class="block-content">
			<ul class="level1">
				//Build sub category menu
				foreach($subcategories as $subcategory): 
					//Get sub sub categories
					$subsubcategories = $subcategory->getChildren();
					//Number of sub sub categories
					$subsubcategoriescount = $subcategory->getChildren()->count();?>
					<li class="level1<?php if($subsubcategoriescount > 0): ?> parent<?php endif; ?>">
					<a href="<?php echo $helper->getCategoryUrl($subcategory) ?>" <?php if ($this->isCategoryActive($subcategory)): ?>class="active"<?php endif; ?>><?php echo $this->escapeHtml(trim($subcategory->getName(), '- ')) ?></a>
					//Display sub sub categories if sub category is active
					if ($this->isCategoryActive($subcategory) && $subsubcategoriescount > 0): 
						<ul class="level2">
							<?php foreach($subsubcategories as $subsubcategory): ?>
							<li class="level2">
								<a href="<?php echo $helper->getCategoryUrl($subsubcategory) ?>" <?php if ($this->isCategoryActive($subsubcategory)): ?>class="active"<?php endif; ?>><?php echo $this->escapeHtml(trim($subsubcategory->getName(), '- ')) ?></a>
							<?php endforeach; ?>
					<?php endif; ?>
				<?php endforeach; ?>
		<?php endif; ?>
	<?php endforeach; ?>
<?php endif; ?>

See below for a quick wirefame mockup of how it should look:

Displaying Sub Categories on Category Landing Page in Magento

The below code snippet/instructions will display images and links for each sub category on a category landing page. Feel free to use this code as a reference, however not being a PHP developer there may well be errors so I welcome any tips or improvements!

1. Create a new file called “categoryblocks.phtml” in app/design/frontend/YOUR THEME/default/template/catalog/navigation

2. Paste the following code into it and save:

//If there are sub categories
$categories = $this->getCurrentChildCategories();
$categoriescount = $this->getCurrentChildCategories()->count();
if ($categoriescount > 0): 
<div class="sub-category-container">	
	//Loop through categories
	foreach ($categories as $category):
	<div class="sub-category">
		<a href="<?php echo $this->getCategoryUrl($category)?>" class="cat-image">
		// If there is a thumbnail set for the category - Display it
		if($imgUrl = Mage::getModel('catalog/category')->load($category->getId())->getThumbnail()):?>
		<img src="<?php echo $this->getBaseUrl()."media/catalog/category/".$imgUrl ?>" width="220" height="110" alt="<?php echo $this->htmlEscape($category->getName()) ?>" />
		<?php endif; ?>
		<div class="inner-sub-category">
			<a href="<?php echo $this->getCategoryUrl($category)?>" class="sub-link"><?php echo $category->getName()?></a>
			<a href="<?php echo $this->getCategoryUrl($category)?>" class="btn"><span>View All</span></a>
	<?php endforeach; ?>
<?php else:?>
<p>No Sub Categories</p>
<?php endif; ?>

3.Create a static block in Magento Admin called “categorylanding”

4.Place the following code snippet into the static block and save.

{{block type="catalog/navigation" template="catalog/navigation/categoryblocks.phtml"}}

5. Go to Manage Categories in Magento Admin and select “categorylanding” as a static block for the categories you wish to display sub categories for.

This should generate something like this:


You can style however you want using the classes provided or by editing to suit your requirements.

Facebook like button – Display the images and content you want.

When a user likes your site using the facebook like button. Facebook posts an image, a link and a description to their wall. But how do you get facebook to show the image and text you want it to display? Afterall this is a good way to advertise and an opportunity not to be missed.

By inserting a couple of metatags (open graph tags) into the head of your page you can select the content you wish to display really easily. You can find comprehensive information on how to do this on the facebook developer site.

However I am going to give you a quick summary of my interpretation of this information.

The header of your site should contain the following:

<!DOCTYPE html>
<html xmlns="" xmlns:og="" xmlns:fb="">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Your Page Title</title>
            <meta property="og:title" content="Site Page Title Goes Here"/>
            <meta property="og:type" content="article"/>
            <meta property="og:url" content=""/>
            <meta property="og:image" content="">
            <meta property="og:site_name" content="Site Title"/>
            <meta property="og:description" content="A description of your site"/>
            <meta property="admins" content="12345"/>

Notes on the above code:

  • Ensure you have all the extra information required after
  • og:title should be your page title
  • og:type should be set to article. There is a wide range of types available however article seems to be the most relevant for a page that is transient. eg a blog post or marketing landing page. Article also seems the most reliable option and produced the least amout of errors for me in facebook lint.
  • og:url This should be your website url and the page you have this code on. This may sound stupid but the url must be url of the page with this code on! Modifying this to the live url (before the page is live) will mean facebook cannot find the correct image path.
  • og:image This should be the path to a thumbnail image of your choice.
  • og:description A short description of your page.
  • admins Despite facebook suggesting you use “fb:admins” I found this to be buggy. “admins” seems to be more reliable. You can find out your facebook admin by clicking on an image within your photo album and looking at the url for the numbers proceeding ?fbid= e.g

Verifying your code
You can check your code by using Facebook Lint Tool. This will let you know any mistakes and also make facebook aware of your page.

Hopefully the above code helps! More information on Open Graph Tags or the like button can be found on the facebook developer website.

HTML 5 – Page Structure

Having built this site using HTML5. I thought it would be good to share a few of my learnings, resources and tips that I have picked up along the way.

As far as I can gather there is absolutely no reason why not to start using the HTML5 doctype. Its short and simple to write and completely backwards compatible. Well the doctype at least. Most of the new features are not, but some do degrade nicely, especially some of the new form elements. As long as you are aware what features have cross browser compatibility issues then you are good to go.

<!DOCTYPE html>

Page Structure
As you can see by viewing the source code of this site I have started implementing some of the new HTML5 tags. In particular:

<header> – For containing header content. A good replacement for <div id=”header”></div> or whatever <div> you might have used to hold your logo or main page heading content. This tag can also be used for content headers or other heading sections on your page. Feel free to use this tag multiple times if needed.

<hgroup> – Used to wrap several heading tags (h1,h2,h3,h4 etc) if they should be read together. Such as a main title and its sub title.

<section> – Exactly what it says. Used to wrap sections of your page. This will probably end up replacing alot of <div> tags.

<article> – Most likely to be used in blogs or news sections. Wraps each piece of news or each publication.

<footer> – Very similar to the header tag. This would most likely replace your <div id=”footer”></div> or the last section of your page. It can also be used multiple times if required.

To see these tags in action I have put together a really simple site structure as an example:

<!DOCTYPE html>
<html dir="ltr" lang="en-US">
<title>This is a test</title>
<header>This is the main header of the page</header>
            <h1>Header of this section</h1>
            <h2>Sub heading of this section</h2>
    <p>Content for the section</p>
    <footer>Footer of this section</footer>
<footer>This is the footer for the page</header>

You can also see an example of the tags in use by viewing the source of this page.

The biggest benefit of the new HTML5 tags is achieving really semantic code. If written correctly your page should have a really logical structure. A good way to check if your code is well written is to use one of the following links:

Cross browser compatibility
To ensure that our new tags are rendered correctly by all browsers, we need to add a small piece of css to set these elements to display as block level elements. This way we can style them in the same way we would the <div> tag.

article, aside, canvas, details, figcaption, figure, footer, header. hgroup, menu, nav, section, summary{display:block}

For IE we need to add some javascript. Setting the elements to display block is not enough. IE doesnt recognise the tags and therefore will completely ignore any styling on them. Using the below JS will fix this problem.

Some of my favourite HTML5 resources at the moment are:

Insites Tour 2011

Last week I attended the London leg of the Insites Tour. It was a great evening with some interesting stories/biographies from the speakers and lots of networking. However reflecting back on it now, I am not sure how much I personally took away from the evening. Having been to this, I have decided I think I may favour the normal conference style format with code and design slides/presentations. Does that make me a little geeky? Or maybe i am just greedy and would like a little of both!

A quick pic from my iphone…

WordPress Custom Post and Custom Taxonomy Permalinks

I have the following setup:
– A custom post type called Products.
– A custom taxonomy called Product Categories.
– A page called Products with a custom page template assigned to it. This page template allows me to query my custom posts and display them in a layout of my choosing. Slug is set to /products.

I wanted my urls for my products to display in the following way:

Or to be more specific:
– View my “Products” page set with the custom template at the url /products
– View each “Product Category” on a url of /products/product-category
– View my custom post type “Products” on a url of /products/product-category/product-name

But nothings ever easy. The trouble I was having was that both my product page and product post type wanted to use the same slug (/products) and therefore conflicted causing 404’s. Not only that but custom taxonomies by default do not show the category in the url, and finally although in my head it made sense as a user to see the url /products/product-category/product-name they were not in any kind of heirarchical structure within wordpress to order them in a url this way.

So after a lot of googling and after finding this really helpful article I finally managed to put together some code that fixed the problem.

add_action( 'init', 'register_custom_post_types' );
//Set up Product Post Type
function register_custom_post_types() {
	register_post_type('products', array(
		'label' => __('Products'),
		'singular_label' => __('Product'),
		'public' => true,
		'show_ui' => true,
		'capability_type' => 'post',
		'hierarchical' => true,
		'rewrite' => array( 'slug' => 'products/%productcats%' ),
		'publicly_queryable' => true,
		'query_var' => true,
		'has_archive' => true,
		'supports' => array('title','editor','thumbnail','excerpt'),
        //Set up Product Categories
	register_taxonomy('productcats', 'products', array(
		'hierarchical' => true,
		'label' => 'Categories',
		'singular_label' => 'Category',
		'rewrite' => array( 'slug' => 'products' ),
//Fix Permalinks
add_filter('post_link', 'product_permalink', 10, 3);
add_filter('post_type_link', 'product_permalink', 10, 3);
function product_permalink($permalink, $post_id, $leavename) {
	if (strpos($permalink, '%productcats%') === FALSE) return $permalink;
		// Posts
		$post = get_post($post_id);
		if (!$post) return $permalink;
		// Custom Taxonomy
		$terms = wp_get_object_terms($post->ID, 'productcats');
		if (!is_wp_error($terms) && !empty($terms) && is_object($terms[0])) $taxonomy_slug = $terms[0]->slug;
		else $taxonomy_slug = 'uncategorized';
	return str_replace('%productcats%', $taxonomy_slug, $permalink);
//Flush permalinks
flush_rewrite_rules( false );

For a step by step explanation of the permalink function please refer to the original article I found on google. You may find you need to go to settings/permalinks in your admin and save again for the changes to take effect. You will already need to have the custom permalink structure set to /%postname%. More information on setting up custom page templates, custom post types and custom taxonomies can be found on the wordpress codex.

Learning JQuery

Over the past year I have been considerably brushing up on my JQuery skills. I thought I would take this opportunity to give a few pointers to others who may be a little nervous about taking their first JQuery steps.

1. Debugging
The best thing I learnt was how to use console.log() in firebug.
console.log() is great way of checking your code as you go. Its far less annoying than using alert() because you can see what is going on behind the scenes without nasty popups to keep closing.
You can use it to check that the selectors you are targeting are correct or that the script you are including has been included correctly.

2. Reading
A really friendly book to get you started is JQuery from Novice to Ninja by sitepoint. Its really easy to understand and has some nice tutorials to get you going.

3. Making use of JQuery documentation
Pretty much all you need to know is on the JQuery official site. Take some time to look around and understand the difference between events, selectors and traversing. Once you know how it all fits together its easy to reference whatever you need. All docs have real source code examples too.

4. Comment your code
It goes without saying that commenting your code whatever language, is good practice. It not only helps you but everyone when maintaining code in the future.

Whilst learning, I think it is a good idea to comment as much as possible. I found that I might copy and paste some code from somewhere (not necessarily the best approach I have to say but it does start to make you more familiar with seeing JQuery) and then modify it to fit what I needed. Its really easy in the early days of learning JQuery to do this and then forget later why or what is going on. Simple commenting of each line of code in laymans terms forces you to learn and understand what the code is actually doing.

5. Write it down before hand
A colleague of mine told me to do this so many times. If you write down what you want to achieve in simple terms on a piece of paper it helps you break down a daunting task into more manageable chunks. e.g click the button, fade in the div etc

A few good tutorial/reference sites:

50 JQuery Snippets
JQuery Videos
JQuery for Designers

WordPress to end support for IE 6

I’ve just been checking out the release notes for the upcoming WordPress 3.2 and it came to my attention that they will  no longer be providing support for IE6. Yippeeeee!

It would seem that the argument for dropping support for IE6 is starting to have some real weight behind it. With WordPress following in the footsteps of many other big names over the last 18 months including Google, YouTube and finally Microsoft themselves it looks like the task of convincing clients to apply the method of graceful degradation is going to become a much easier task.

WordPress Comments Form – How to change HTML

I searched high and low for a good tutorial on how to change the HTML of the wordpress comment form. From the articles I did find I managed to put together something that works. Feel free to post a comment if there is a better way of doing this…

I put the below code in functions.php and comment_form(); in my comments.php

The code below is my modified version. For defaults simply add or replace my code with

add_filter( 'comment_form_defaults', 'my_comment_defaults');
function my_comment_defaults($defaults) {
	$req = get_option( 'require_name_email' );
	$aria_req = ( $req ? " aria-required='true'" : '' );
	$defaults = array(
		'fields'        	   => array(
		'author' => '<div><label for="author">' . __( 'Name' ) . ( $req ? '<span class="required">*</span>' : '' ) . '</label> ' . '<input id="author" name="author" placeholder="your name" type="text" value="' . esc_attr( $commenter['comment_author'] ) . '" size="30"' . $aria_req . ' /></div>',
		'email' => '<div><label for="email">' . __( 'Email' )  . ( $req ? '<span class="required">*</span>' : '' ) . '</label> ' . '<input id="email" name="email" placeholder="" type="email" value="' . esc_attr(  $commenter['comment_author_email'] ) . '" size="30"' . $aria_req . ' /></div>'
		'comment_field' => '<div><label for="comment">' . _x( 'Comment', 'noun' ) . '</label><textarea id="comment" name="comment" cols="45" rows="8" aria-required="true"  placeholder="your comment"></textarea></div>',
		'must_log_in'          => '<p class="must-log-in">' .  sprintf( __( 'You must be <a href="%s">logged in</a> to post a comment.' ), wp_login_url( apply_filters( 'the_permalink', get_permalink( $post_id ) ) ) ) . '</p>',
		'logged_in_as'         => '<p class="logged-in-as">' . sprintf( __( 'Logged in as <a href="%1$s">%2$s</a>. <a href="%3$s" title="Log out of this account">Log out?</a>' ), admin_url( 'profile.php' ), $user_identity, wp_logout_url( apply_filters( 'the_permalink', get_permalink( $post_id ) ) ) ) . '</p>',
		'comment_notes_before' => '<fieldset>',
		'comment_notes_after'  => '</fieldset>',
		'id_form'              => 'commentform',
		'id_submit'            => 'submit',
		'title_reply'          => __( 'Leave a Comment' ),
		'title_reply_to'       => __( 'Leave a Reply %s' ),
		'cancel_reply_link'    => __( 'Cancel reply' ),
		'label_submit'         => __( 'Comment' ),
    return $defaults;

You will notice I have made the following modifications

  • Removed the website field
  • Added type=”email” to the Email field (HTML5)
  • Added placeholder text (HTML5)
  • Removed the default text from the top and bottom of the form and replaced with <fieldset></fieldset>
  • Moved the required * inside the label
  • Changed the “Leave a Reply” title to “Leave a Comment”
  • Changed the text of the submit button

WordPress 404 on Custom Post Types

I came across a nightmare of a problem today. Everytime I viewed my custom post types I kept getting a 404 error.  I just couldnt understand what was going on.  Thanks to this article I finally solved the problem.

When setting up custom post types and a custom permalink structure add the below code to the function used to create custom posts.

flush_rewrite_rules( false );

I just wanted to write a quick post to highlight the problem but an explanation of why this is needed can be found on the wordpress codex.

WordPress Tips, Tutorials and Plugins

I thought I would put together a quick list of tips, tutorials and plugins that I have found useful recently.

1. Getting Thumbnail Images working in WordPress Multisite:

Something that really baffled me over the last week is missing post thumbnails in my WordPress Multisite Install. After searching high and low I finally found the solution. To enable post thumbnails simply navigate to Network Admin (top right hand corner) and then to Settings.  Within Settings tick the check box for Image Uploads. You may then need to navigate to Screen Options (top right hand corner again) and tick the check box for Featured Image. This will also enable the small image icon above the WYSIWYG used for adding images into the post itself. Video etc can also be enabled in the same place.

2. Mixing together custom post types in listing

So you’ve created several post types, one for portfolio items, one for products etc etc but instead of displaying them on their own individual listing pages you need to mix them together in the same loop and order by date… Here is the answer. Place the below code before your loop to query the custom post types you require.

query_posts( array(
'post_type' =&gt; array(
'paged' =&gt; $paged ) // for paging

3. How to use a plugin in your template if only a shortcode is provided

As soon as I download a plugin I search through the documentation to find the template tag. Maybe its a bit old school but I prefer to add plugins into my templates so that I can place them exactly where I want, configure them as I need and style around them. But sometimes all your provided with is a shortcode. These can be turned into template tags by following these instructions.


<span>add_<span>shortcode</span>('<span>shortcode</span>_name', 'template_tag');</span>

Your template

<span>echo do_<span>shortcode</span>("[<span>plugin</span>_<span>shortcode</span>_here]");</span>

4. Multiple Content Blocks
Something that has always bugged me about WordPress is the inability to split page content into manageable CMS chunks. Yes you can create custom fields and custom sidebars but what happens when there is a whole block of content that you would like the user to have WYSIWYG editing control over? The answer is this plugin Multiple Content Blocks It does exactly what it says on the tin and transforms WordPress into a functional CMS much along the lines of Drupal and CMS Made Simple. Love it!

5. Popular posts & Related Posts
Its pretty popular these days to have a section on a site displaying the most popular post or related posts. My all time favourite plugins for this are by Rob Marsh. Simple and easy to configure Robs plugins although slightly old these days still provide the best configuration options and are easy to template and style.

How to use Post Formats in WordPress 3.1

WordPress 3.1 has seen the introduction of Post Formats. They provide the ability to target posts within templates using get_post_format() and through css using the extra classes wordpress now adds automatically to posts. This will save on creating extra categories or tags just for targeting and styling these types of content.

So how does it work…

Add this to the functions.php file in your theme. You only need to list the formats you wish to use.

// This theme uses post formats<br/>
add_theme_support( 'post-formats', array( 'aside', 'gallery', 'link','image', 'quote', 'status', 'video', 'audio', 'chat' ));

You will then see a list of radio buttons in your edit post right hand column.

Once a type is selected you can style using the following class added to your post on listing pages

and using the following class added to your tag on single pages.

Within your templates you can target posts by format using the following code

 if ( has_post_format( 'image' )) {
  echo 'this is an image format';

WordPress 3.1

Yesterday saw the release of WordPress 3.1 and it has some pretty nice features for both general users and developers like myself.

New Admin Bar
An admin bar has been added when logged in. Its a nice little touch for the not so experienced wordpress user. It makes the admin section and the front end appear more seamless by allowing you to click through to create a new post, manage your personal details, appearance, comments and updates whilst browsing the front end of your site. For multisite users it makes switching between sites quick and easy.

Continue reading

Google PAC-MAN

I love google homepages. They are always really creative, original and a great way to learn about special days in the year.

This one however has to be my all time favourite. Its PAC-MAN’s 30th Birthday and to celebrate they have designed a google game for everyone to enjoy. Its great and even has an insert coin button for two players. Enjoy Everyone!

How did I not know about the col tag???

So whilst developing away the other day I came across the <col> tag! ( Hopefully I am not alone in never having used this before.)
After a quick google I soon established that the col tag could be used to control the widths and alignments of columns in a table removing the need to constantly define td widths and alignments individually.
Continue reading