1. Home
  2. Prices
  3. Guided Tour
  4. New Shop
  5. Shop Review
  6. Ecommerce Marketing
  7. Ecommerce TV
  8. Magento Developers
  9. Portfolio
  10. Blog
  11. Contact

Magento Tutorials

Archive for the ‘Magento Tutorials’ Category

Customise Navigation Menu Links

Posted on: 18th Jun 2010 By: Robert Kent 1 Comment

The navigation menu in magento is more versatile than it seems. Obviously the menu does what it needs to do – list categories and subcategories in their respective positions. However recently I got a request to manipulate the menu and make some things click-able and others not click-able.

The client wanted only the landing pages to be links – this meant that any list item with a drop down list appearing off of it would not be click-able – however all the ending pages – such as the subcategories had to be linked. Another interesting one was that they still wanted the main categories to be links – even though they have drop downs coming off them…strange huh?

I’m not quite sure what the purpose of this exercise was but apparently it made more sense to their e-commerce web design if the menu acted this way, however bad it may seem for SEO purposes.

I thought that this could be useful for some people so I have decided to share it here on our magento blog. The magento fox may even tweet about this too.

First of all I found the core code that needs editing – the drawItem() function. You can find this in the app>code>core>Mage>Catalog>Block>Navigation.php.

As always you should make a local copy of this file so that when upgrading magento your changes are not undone.

In Navigation.php you will find the function drawItem() all you have to do is replace the part that includes the <anchor tag> with a version with no <anchor tag>. The tricky part is determining which items get the links and which do not.

Find this line in your code:

$html.= '<a href="'.$this->getCategoryUrl($category).'"><span>'.$this->htmlEscape($category->getName()).'</span></a>'."\n";

And replace with:

if($hasChildren && $level != 0){
$html.= '<span>'.$this->htmlEscape($category->getName()).'</span>'."\n";
} else {
$html.= '<a href="'.$this->getCategoryUrl($category).'"><span>'.$this->htmlEscape($category->getName()).'</span></a>'."\n";
}

This should make immediate sense to any magento user – basically if the level is not 0 (i.e NOT the main categories) and also if it has children (has drop downs coming off) then don’t add an anchor tag around the text. Something that I thought would be really hard to achieve was actually really easy and completed in 5 minutes.

If you found this blog useful please leave a comment and let me know, I’d love to hear the situations where you would need to use this code because at the moment, just like that darn magento fox, it’s eluding me.

Show Magento Products by Attribute

Posted on: 17th Jun 2010 By: Adam Moss No Comments

You may remember Rob’s recent post about Smart Product Lists which detailed how to bypass Magento’s usual database interactions, and get straight in there yourself with your own MySQL code. Putting this to good use the other day I developed this script which does something so simple, yet can be quite difficult if you don’t know where to start. Trust me, I checked the Internet and there’s nothing out there which helps you do this.

What I needed to was print out all the products in the store which contained the words ‘Full Colour Printing’ in the attribute ‘pen_feature’. So, if anywhere in the string the words ‘Full Colour Printing’ appear, my script will tell the product name along with the product link to appear on the CMS page that I implemented it on. I’ll go through the code step by step:

1. First we need to inlcude the Magento Database Connection.

require_once 'app/Mage.php';
Mage::app('default');

2. Next we need to create an SQL statement and run a query which would effective grab every product ID contained in the store and store it in $result. In my case that was over 300 products. The ORDER BY bit isn’t necessary as it will probably put them in order anyway!

$write =  Mage::getSingleton('core/resource')->getConnection('core_write');
$result  = $write->query("SELECT product_id FROM catalog_category_product  ORDER BY product_id");

3. Now I’m going to write a while loop which will only execute the rest of the script while the $result can retrieve database data. Each row is now deliverers as a string, which means you’ll have a long list of numbers in one variable… not very helpful. So, I’m going to create a new variable, $prodid, which will become an array of all the product IDs by simply exploding the numbers at each blank space. Bingo – we now have a beautiful array of product IDs.

while ($row = $result->fetch() ) {

$prodid = explode(" ",  $row['product_id']);

4. Now for a bit of Magento code. I’m gonna start with a foreach statement which will convert $prodid into $id, then I’m going to load the Mage product data into each loop, each time the product being loaded by its ID.

foreach ($prodid as $id) {

$_product = new  Mage_Catalog_Model_Product();
$_product->load($id);

5. Now, I need to narrow down all these products so that it only brings out the ones with ‘Full Colour Printing’ within the pen_features attribute. So I load the attribute as $feature, and I create a variable for ‘Full Colour Printing’. Now I can use strpos with $feature as the haystack and $fullcol as the needle. With that check in place, one more if statement around the echoed script will check if the $fullcolcheck is true or not.

$fullcol =  "Full Colour Printing";
$feature =   $_product->getResource()->getAttribute('pen_features')->getFrontend()->getValue($_product);

$fullcolcheck = strpos($feature, $fullcol);

if ($fullcolcheck !==  false) { ?>

6. Now it’s simply a case of bringing out the product data, remember we’re still inside that foreach and while loop! You could bring out much more such as the price or image too.

<li><a href="<?php echo $_product->getProductUrl()  ?>"><?php echo $_product->getName();  ?></a></li>

That’s really all there is too it – not bad eh? You can probably simplify this script even more as it’s unlikely you’ll need to use the strpos if you’re checking attributes. I’ve put the entire script below for you to use as you wish. Keep checking back at the Magento Blog at Ecommerce Web Design for more of our Magento tutorials.

<ul><?php

require_once 'app/Mage.php';
Mage::app('default');

$write =   Mage::getSingleton('core/resource')->getConnection('core_write');
$result  = $write->query("SELECT product_id FROM  catalog_category_product  ORDER BY product_id");

while ($row = $result->fetch() ) {

$prodid = explode(" ", $row['product_id']);

foreach ($prodid as $id) {

$_product = new Mage_Catalog_Model_Product();
$_product->load($id);
$fullcol = "Full Colour Printing";
$feature = $_product->getResource()->getAttribute('pen_features')->getFrontend()->getValue($_product);

$fullcolcheck = strpos($feature, $fullcol);

if ($fullcolcheck !== false) { ?>
<li><a href="<?php echo $_product->getProductUrl() ?>"><?php echo $_product->getName(); ?></a></li>
<?php } } } ?></ul>
Categories: Magento Tutorials Tags:

Making Links Local in Magento

Posted on: 16th Jun 2010 By: Luci Smethurst 3 Comments

One of the lovely built-in issues with Magento is that all the links it generates are external – ie it will always preface the link with the domain, like this: http://www.domain.co.uk/category.html. This is a Bad Thing in terms of SEO – and what’s the point of having a brilliant e-commerce web design if the search engines don’t like it? Don’t worry, a solution can be found right here on the Magento blog. Read on, avid readers!

The solution is actually relatively simple – just add a string replace onto any links you would like to be local, for example on the getChildHtml include in your head.phtml file:

echo str_replace("http://www.domain.co.uk/", "/", $this->getChildHtml());

- replace www.domain.co.uk with your domain name and it will replace all instances of it with a /.

However, all is not well in the getCssJsHtml include. This little function is the reason why it’s not as simple as it could be – it pulls in all the CSS, JS and HTML tags that you see in the tag, which sounds brilliant in theory, but if you have enabled canonical links it’s actually a Bad Thing.

Why, you ask?

Because the wonderful string replace tags we used earlier will find all instances of your domain name (for example www.e-commercewebdesign.co.uk) and replace them with a / – including in the generated canonical link tags.

All is not lost however. We’ll just separate the likes of the canonical links from the Css, Js and other Html tags… like two naughty children in a playground.

  • Go to your getCssJsHtml() function
  • Find the section helpfully labelled “other stuff” (about line 211), copy the code and delete it from the function:
	// other stuff
            if (!empty($items['other'])) {
                $html .= $this->_prepareOtherHtmlHeadElements($items['other']) . "\n";
            }

            if (!empty($if)) {
                $html .= '<!--[endif]-->'."\n";
            }
  • Create a new function, I’ve called my getOtherHeadLinks()
  • Paste in the code you’ve just copied
  • Now, that code isn’t enough on it’s own, we also need to tell all the whither-to’s and why-fors, so we add some more code above the “other stuff” so that you end up with the function below, and hey presto, you’ve got a working function and separate canonical links!
  public function getOtherHeadLinks()
    {
        // separate items by types
        $lines  = array();
        foreach ($this->_data['items'] as $item) {
            if (!is_null($item['cond']) && !$this->getData($item['cond']) || !isset($item['name'])) {
                continue;
            }
            $if     = !empty($item['if']) ? $item['if'] : '';
            $params = !empty($item['params']) ? $item['params'] : '';
            switch ($item['type']) {
                default:
                    $this->_separateOtherHtmlHeadElements($lines, $if, $item['type'], $params, $item['name'], $item);
                    break;
            }
        }

        // prepare HTML
           $html   = '';
        foreach ($lines as $if => $items) {
            if (empty($items)) {
                continue;
            }
            if (!empty($if)) {
                $html .= '<!-- [if '.$if.']-->'."\n";
            }

			// other stuff
            if (!empty($items['other'])) {
                $html .= $this->_prepareOtherHtmlHeadElements($items['other']) . "\n";
            }

            if (!empty($if)) {
                $html .= '<!--[endif]-->'."\n";
            }

        }
        return $html;
    }

Magento User Permissions

Posted on: 8th Jun 2010 By: Robert Kent 1 Comment

OK, so as a magento developer you have just created a fantastic Magento website for a customer. You have included all the tips and tricks that you know and really gone to town on it. You now have to pass the reigns over to the customer…sometimes this can be like handing over you brand spanking new Audi R8 to you kid brother for a test drive…a stressful experience, one which I have had to deal with on many an occasion. The Magento store handover that is – not the Audi R8, that baby is all mine.

It is important that you protect the vital areas of your Magento store. There are places within the admin section that are dangerous to the untrained user. You can spend an entire day teaching your customer how to manage the configuration side of the back-end but all it takes is one slip up, one moment of madness, and you will be spending the next 48 hours trying to piece together why the customer has rang up and complained that their site is currently looking like the rear end of some large hairy animal…

User Permissions! This is the term that you should all become familiar with. Those of you who have had experience in Wordpress should know all about user permissions, whether you are creating a user with the ability to change wordpress preferences or simply be restricted to writing and editing blogs – the principle is exactly the same in Magento.

In Magento there are two ways to create users and assign them a role, I will choose the role creation method first which is the easier way but you can reverse these two steps and the outcome will be the same.

To create user permissions for the average store owner here is what you do:

1.Creating the Role

First of all, when logged in as admin you should navigate to system>permissions>roles.

Click the button top right and create a new role.

Enter your role name (something like ’store owner’) and then click on the tab called Role Resources on the left.

This is where things get interesting, you should probably take your time and go through these and try to match them up in the navigation in your admin section. Really, for a shop owner you should probably tick all the boxes except the system box – and all the boxes within system. This way you leave the customer enough options to manage the store effectively without giving away anything too dangerous. When you are done you should see something like the image on the right.

2. Creating the User and assigning the Role

Now we have our ‘Store Owner’ role created and limited it to the non-vital, catastrophe-free areas of the site we can now create our Store Owner login and assign them this role.

After you have saved your role navigate to system>permissions>users. Choose to add a new user from the top or alternatively you can select an already active user and change their permissions from here.

Choose your username and password etc for the user and then click on the left tab that says User Role. You can now click on your ’store owner’ role and click save.

Now you have successfully created a brand new user – log in as them and you will see your limited menus in effect! Cool huh?

If you use this wisely you can really benefit your customers, creating different groups for each of their departments – say you wanted someone to manage just the newsletters – only give them access to the newsletter section, if you wanted someone to add new products but not categories – simply let them access the manage products section!

The possibilities are endless!

Thanks for visiting our magento blog at ecommerce website design. I hope you enjoyed this post and please leave some feedback of your own or if you have any questions or queries just let us know – we want to hear them!

Smart, Sortable Product Lists

Posted on: 4th Jun 2010 By: Robert Kent No Comments

There comes a time in everyone’s life when you need to do a little sorting. Whether this is sorting your room or sorting out relationships some form of arrangement and re-arrangement of data/things/spouses is required. When it comes to magento you may want to do the same thing to your store.

The following code and file is not simply a finished product for you to take away and use and that’s the end of it, it’s more of an open source compilation written outside of magento for people to have a quick look at their product listings – it acts almost like the exported spreadsheet from the back end but you can adapt this file in any way you like to bring out any data you want! Depending how creative you are you can do almost anything with the code that I have written for you – take it as the foundations to perhaps an entire dynamic product catalogue that someone who may or may not be me, may or may not write in the future…

Smartening up your product lists – simply copy and paste the following file onto your root magento layer and run it in the browser.

Here is the FILE (magentofox-productlisting.php).

Here is the code:

<?php
function msort($array, $id, $sort_ascending=true) {
$temp_array = array();
while(count($array)>0) {
$lowest_id = 0;
$index=0;
foreach ($array as $item) {
if (isset($item[$id])) {
if ($array[$lowest_id][$id]) {
if ($item[$id]<$array[$lowest_id][$id]) {
$lowest_id = $index;
}
}
}
$index++;
}
$temp_array[] = $array[$lowest_id];
$array = array_merge(array_slice($array, 0,$lowest_id), array_slice($array, $lowest_id+1));
}
if ($sort_ascending) {
return $temp_array;
} else {
return array_reverse($temp_array);
}
}
?>
<table width="100%">
<tr><td><img src="http://a3.twimg.com/profile_images/949933723/magento-fox.gif" alt="Magento Fox" align="left" /></td><td colspan="3"><h1>Magento Fox Product Listing</h1></td><td>Sorted by <strong><?php if(isset($_GET['sort'])){ echo $_GET['sort']; } else { echo "product_id"; } ?></strong></td></tr>
<tr><th><a href="?sort=category_name">Category</a> (<a href="?sort=category_id">ID</a>)</th><th><a href="?sort=product_id">Product Id</a></th><th><a href="?sort=product_sku">SKU</a></th><th><a href="?sort=product_name">Name</a></th><th><a href="?sort=product_price">Price</a></th></tr>
<?php

require_once 'app/Mage.php';
Mage::app('default');

// Setting up our Array structures

$category_array = array();
$product_array = array();

$write = Mage::getSingleton('core/resource')->getConnection('core_write');
$readresult=$write->query("SELECT product_id, category_id FROM catalog_category_product ORDER BY product_id");

while ($row = $readresult->fetch() ) {

$write2 = Mage::getSingleton('core/resource')->getConnection('core_write');
$readresult2=$write2->query("SELECT sku FROM catalog_product_entity WHERE entity_id = ".$row['product_id']." LIMIT 1");

$prodid = $row['product_id'];
$catid = $row['category_id'];
while ($row2 = $readresult2->fetch() ) { $sku = $row2['sku']; }

$_product = new Mage_Catalog_Model_Product();
$_product->load($prodid);
$_category = new Mage_Catalog_Model_Category();
$_category->load($catid);

$products[] = array("category_name" => $_category->getName(), "category_id" => $catid, "product_id" => $prodid, "product_sku" => $sku, "product_name" => $_product->getName(), "product_price" => $_product->getFinalPrice());

}
if(isset($_GET['sort'])){
$products = msort($products, $_GET['sort']);
}
$myx = 0;
foreach($products as $prod){ ?>
<trzero"; $myx = 1; } else { echo "one"; $myx = 0; } ?>"><td><?php echo $prod["category_name"]; ?> (<?php echo $prod["category_id"]; ?>)</td><td><?php echo $prod["product_id"]; ?></td><td><?php echo $prod["product_sku"]; ?></td><td><?php echo $prod["product_name"]; ?></td><td>&pound;<?php echo number_format(round($prod["product_price"], 2), 2); ?></td></tr>
<?php } ?>
</table>

Here is the output:

Here is how it works:

What you see here is the output of our php file – the file connects to magento and extracts the product list from the database. It then loads the category and the products and outputs the data required.

I notice I have made a small error here and ran the SKU as a separate mysql command. This could be transformed to $_product->getSKU() I’m guessing but as I said before it really is yours to play with.

Next we run a command that stores the values we return into a nice array. This array is then outputted into a table format. We can sort this table by clicking on the table headings – this will create a get function and sort the array before it is outputted.

Warning - this code outputs ALL of your products – I tried it on a store with 750 products on and it took 20 seconds to load the page. Use this as a rule of thumb – however I would recommend adding a form of pagination to this code and also limiting the sql array to something smaller like 50 per page.

(to do the limit simply add LIMIT 50 after the PHP code on line 57 of the file).

I hope this is of use to someone and thank you for visiting our magento blog at ecommerce website design!