Page 1 of 41234

Force HTTPS on Magento Shopping Cart Pages & Admin Backend

After you have installed SSL certificate for your eCommerce site and the HTTPS version of your domain is successfully accessible, Magento doesn’t automatically use HTTPS for some of the important pages across the site, such as /checkout/cart/, /customer/account/, etc.

Enable HTTPS for your Magento store

You have to explicitly enable HTTPS for your Magento store if you didn’t select HTTPS during installation.

In the Admin panel: System -> Configuration -> General -> Web -> Secure

  1. Base URL – https://www.yoursite.com
  2. Use Secure URLs in Frontend – Yes
  3. Use Secure URLs in Admin – Yes

Now Magento should be using HTTPS:// for all the important frontend pages (/customer/account/, /checkout/onepage/, etc.) and across the entire backend Admin pane.

Wait, /checkout/cart/ is still not HTTPS!

Yep. You have to do one more thing to make sure /checkout/cart/ is also automatically HTTPS.

Edit app/code/core/Mage/Checkout/etc/config.xml, find this:

<frontend>
<secure_url>

And add this line immediately below:

<checkout_cart>/checkout/cart</checkout_cart>

So that it looks like this:

<frontend>
<secure_url>
<checkout_cart>/checkout/cart</checkout_cart>
<checkout_onepage>/checkout/onepage</checkout_onepage>
<checkout_multishipping>/checkout/multishipping</checkout_multishipping>
</secure_url>

Refresh all the cache and Magento should be using HTTPS on /checkout/cart/ now.

Add Sort by "Date" to Magento Catalog Products List

Magento has only 3 pre-defined sort methods for catalog products list, namely by Position, Name, and Price. It’s not unusual that the customers or catalog editors would want to sort the products by creation date so that the newest products are displayed at the forefront. We will make this happen in this article.

Step 1

Find file /app/code/core/Mage/Catalog/Model/Config.php and copy it to /app/code/local/Mage/Catalog/Model/Config.php. Open the copied file (open it still if it already exists before the copy) and find this function.

Add the bolded line:

public function getAttributeUsedForSortByArray()
{
    $options = array(
        'position'  => Mage::helper('catalog')->__('Position'),
        // This line that adds the 'Date' option to the Sort By dropdown methods.
        'created_at' => Mage::helper('catalog')->__('Date')
    );
    foreach ($this->getAttributesUsedForSortBy() as $attribute) {
        /* @var $attribute Mage_Eav_Model_Entity_Attribute_Abstract */
        $options[$attribute->getAttributeCode()] = $attribute->getStoreLabel();
    }

    return $options;
}

Step 2

Create and upload this file /app/etc/modules/SortByDate_Catalog.xml

<?xml version="1.0"?>
<config>
    <modules>
    <SortByDate_Catalog>
        <active>true</active>
        <codePool>local</codePool>
        <depends>
            <Mage_Catalog />
        </depends>
    </SortByDate_Catalog>
</modules>
</config>

Step 3

Create and upload this file /app/code/local/SortByDate/Catalog/etc/config.xml

<?xml version="1.0"?>
<config>
<global>
    <models>
        <catalog>
            <rewrite>
                <config>SortByDate_Catalog_Model_Config</config>
            </rewrite>
        </catalog>
    </models>
</global>

Step 4

Create and upload this file /app/code/local/SortByDate/Catalog/Model/Config.php

<?php

class SortByDate_Catalog_Model_Config extends Mage_Catalog_Model_Config {

	public function getAttributeUsedForSortByArray()
	{
		$options = parent::getAttributeUsedForSortByArray();
		if (!isset($options['created_at'])) {
			$options['created_at'] = Mage::helper('catalog')->__('Date');
		}
		return $options;
	}

}

That’s it.

Now refresh your category pages and you would see an additional sort method ‘Date’ in the ‘Sort By’ dropdown list and selecting it would make the catalog display the items by creation date. Clicking the small arrow to the right would toggle between descending order and ascending order.

Add “View” Product Page Link in Backend at Catalog => Manage Products List

The current version of Magento is not editor-friendly in many regards and one of them is that the products list at Catalog => Manage Products doesn’t have any “View” link at the end of each product row for the catalog editor (human) to easily click on to open up the frontend product page to see what the users are actually seeing.

Rather, it has only the “Edit” link to open up the editor to edit the product. If one has to view a frontend product page from the backend, he or she’d have to copy the SKU and then search it in frontend to arrive at the product page which is very unhandy and annoying. Sometimes the results don’t even turn out any entries at all.

WordPress and lots of other famous CMS have this feature and I’m totally at a loss why Magento doesn’t have this ready for the convenience of the backend editors.

So how to add a “View” product link beside the “Edit” link for each product record?

At the end of article, you will have something similar to this:

Add view product links to the end of each product row in Magento

That is, “View” product links on each product row that you can click to open up the frontend product page. Screenshot taken from my wedding dresses store.

To do this, find this file:

/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Grid.php

And copy it to:

/app/code/local/Mage/Adminhtml/Block/Catalog/Product/Grid.php

Open and edit the copied file /app/code/local/Mage/Adminhtml/Block/Catalog/Product/Grid.php, find a block like this:

$this->addColumn('action',
            array(
                'header'    => Mage::helper('catalog')->__('Action'),
                'width'     => '50px',
                'type'      => 'action',
                'getter'     => 'getId',
                'actions'   => array(
                    array(
                        'caption' => Mage::helper('catalog')->__('Edit'),
                        'url'     => array(
                            'base'=>'*/*/edit',
                            'params'=>array('store'=>$this->getRequest()->getParam('store'))
                        ),
                        'field'   => 'id'
                    )
                ),
                'filter'    => false,
                'sortable'  => false,
                'index'     => 'stores',
        ));

Which is the code for the “action” column of the products list. In the same manner, add an extra column named “view” by adding the code below immediately after “action“:

$this->addColumn('view',
            array(
                'header'    => Mage::helper('catalog')->__('View'),
                'width'     => '40px',
                'type'      => 'action',
                'getter'     => 'getId',
                'actions'   => array(
                    array(
                        'caption' => Mage::helper('catalog')->__('View'),
                        'url'     => array(
                            'base'=>'catalog/product/view',
                            'params'=>array('store'=>$this->getRequest()->getParam('store'))
                        ),
                        'field'   => 'id'
                    )
                ),
                'filter'    => false,
                'sortable'  => false,
                'index'     => 'stores',
        ));

That’s it. Now refresh your Manage Products page and you should see a “View” link at the end of each product row. Clicking them would lead you to the frontend page of that particular product. I’m not sure how to force it to open in new window or new tab but I guess you can always do this yourself by holding Ctrl key in Firefox and Chrome.

Bolded part is the key difference of the “view” block from the “action” block.

Add Stats Script Code before Closing in Magento

Not surprisingly, most people believe the right way to do this is to find the *footer* template in the Magento theme and then include the analytics code at the end of the file. While this approach works, it’s not the best, because it’s NOT immediately before </body></html>.

What if you really need to add the code IMMEDIATELY before the page closing tags </body></html>?

Add code immediately before </body></html> in your Magento store

The best intended approach is to supply the code in your Magento System Configuration. Just go to:

System -> Configuration -> Design -> Footer.

Here you will find a textarea field that reads Miscellaneous HTML. Just put the analytics code there and it will appear immediately before the closing </body></html> on every page of your Magento store.

Similarly, add code immediately before closing </head>

Follow the configuration path:

System -> Configuration -> Design -> HTML Head

And you will find a textarea field named Miscellaneous Scripts. Just put any head meta or scripts code there and they will appear immediately before </head> on every page of your Magento store.

 

Set Default Weight, Set Status to be ‘Enabled’ by Default and Tax Class to be ‘None’

Just like the points made from this post: Auto-generated SKU for new product, it’s annoying to have to enter some of the fields every time you create a new product because apparently, we want it ‘Enabled’ in status; weight doesn’t matter so much; and most of the products belong to one tax class or simply ‘None’.

To reduce repeatedly wasted time and increase productivity when creating products, just edit /app/design/adminhtml/default/default/template/catalog/product/edit.phtml and add the following JavaScript to the end of the file:

<script type="text/javascript">
if(document.getElementById('status').value == ""){
    document.getElementById('status').options[1].selected = true;
}
if(document.getElementById('weight').value == ""){
    document.getElementById('weight').value = "1.0";
}
if(document.getElementById('tax_class_id').value == ""){
    document.getElementById('tax_class_id').options[1].selected = true;
}
</script>

Now the Weight field will have a default value of ’1.0′, the Status field is selected ‘Enable’ by default and the Tax Class is selected as ‘None’ by default.

Auto-generated Product SKU when Adding New Product

SKU isn’t needed in all stores and it’s sometimes annoying to have to enter it for every new product. Is there any way for Magento to automatically generate new SKU for new products?

There is.

Open /app/design/adminhtml/default/default/template/catalog/product/edit.phtml and add the following snippet to the bottom of the file:

<?php
    $dbread = Mage::getSingleton('core/resource')->getConnection('core_read');
    $sql = $dbread->query("SELECT * FROM catalog_product_entity ORDER BY created_at DESC LIMIT 1");
    $res = $sql->fetch();
?>
<script type="text/javascript">
if(document.getElementById('sku').value == ""){
    document.getElementById('sku').value = <?php echo (int)$res["sku"] + 1; ?>;
}
</script>

What this code does:

  1. Read the SKU (must be an integer) of the last added product.
  2. Increment the SKU by 1.
  3. Pre-populate the incremented new SKU to the SKU field by JavaScript.

Therefore, you don’t have to manually enter the SKU yourself when adding the product.

You can do more with this

By adding extra JavaScript code to edit.phtml in a similar way, you can set default values for text input fields and make options selected by default for drop-down selections in the product editor.

SEO Friendly Tag URLs for Your Magento Store

By default, you would have a tag URL such as this for your Magento store:

http://www.example.com/tag/product/list/tagId/3/

While it’s perfectly static, it doesn’t look good without tag names in the URL nor does it inspire trust. We want it to be more neater as:

http://www.example.com/tag/royal/

It’s actually a very simple problem that’s ready to be solved if you are willing to spend $39 bucks. Iceberg Commerce has the exact solution: Magento SEO Product Tag Urls

Simply purchase the package, download it, uncompress and upload the app directory to your store installation. It’s upgrade-proof because they are well separated from the rest of the system. You don’t even have to overwrite any files.

Clear your Magento cache and you would see SEO-friendly tag URLs all over your store: individual product page, tags list page, etc.

They’ve got also a lot of other interesting and useful extensions for your Magento store.

Malicious / Spam Search Terms in Magento Popular Search Terms

If you’ve got a fairly popular Magento store, you’ve probably got the problem of spam or malicious search terms showing up on the Popular Search Terms page. It’s ugly and you want to get rid of them once and for all, but at the same time leaving legitimate search terms performed by good-will users intact.

Of course you do. Me too. Look at this:

Magento store spam searches

So how to delete spam search terms from Popular Search Terms page?

What I’ve done is to edit the /app/design/frontend/default/your_theme/template/catalogsearch/term.phtml until it looks something like this:

		<?php
		$princessly_search_term = $this->htmlEscape($_term->getName());
		if (strpos($princessly_search_term, '%') !== false
			|| strpos($princessly_search_term, "'") !== false
			|| strpos($princessly_search_term, '`') !== false
			|| strpos($princessly_search_term, '=') !== false) {
			continue;
		}
		?>
            <li><a href="<?php echo $this->getSearchUrl($_term) ?>" style="font-size:<?php echo $_term->getRatio()*70+75 ?>%;"><?php echo $princessly_search_term ?></a></li>

The PHP function strpos() checks if a specific character is existent in the string $princessly_search_term which contains the originally raw search phrase. If it does, it’s not displayed (continue to the next phrase and check it to see if it does).

Most malicious / spam search attempts contain ‘%’, “‘”, or ‘=’ which normal users wouldn’t use in a legitimate search for your products. Now the Popular Search Terms page is a lot more clean and user friendly.

Display all product images on the product page (view.phtml)

Lots of online stores nowadays are blatantly showing all the sharp and tempting images of the product on the product page. They are all there for you and the visitors to examine one after another simply by window scrolling – no gimmicks such as cloud zooming or lightbox, etc. While technical cleverness such as cloud zooming or lightbox may seem pretty, they are hardly any more usable than the plain old way of just splashing the product images by simple HTML code.

I prefer the old way which would actually engage the visitors.

However, by default Magento has only narrowly arranged thumbnails of the product images, the visitor has to click those thumbnails to see the large version – waste of user attention and they could leave because it costs more to get what they want (to see a larger picture). What we want to do is to simply display all the product images in large versions on the product page where the visitors are instantly satisfied.

Display all product images WITHOUT watermarks

To do this, find /app/design/frontend/default/your_theme/template/catalog/product/view.phtml and add this snippet anywhere appropriate (change the bold part to your own theme path):

<div class="product_images_exhibit">
	<h2><?php echo $this->__('Product Images') ?></h2>
	<?php $_images = Mage::getModel('catalog/product')->load($_product->getId())->getMediaGalleryImages(); ?>
	<?php if($_images) {?>            
		<?php foreach($_images as $_image) {?>
			<p><img src="<?php echo $this->helper('catalog/image')->init($_product, 'image', $_image->getFile())->constrainOnly(TRUE)->keepAspectRatio(TRUE)->keepFrame(FALSE)->setWatermarkImageOpacity(0)->resize(848, null);?>" alt="<?php echo $this->htmlEscape($_image->getLabel());?>" title="<?php echo $this->htmlEscape($_image->getLabel());?>" /></p>
		<?php } ?>
	<?php } ?>
</div>

That’s it! See what I’ve done for my store: http://www.princessly.com/trumpet-a-line-v-neck-asym-drop-waist-sleeveless-straps-wedding-dress-w-court-train.html

Display all product images WITH watermarks

With “->setWatermarkImageOpacity(0)” the displayed images will not have watermarks on them. This is better for user experience but may enable image stealing. To add the watermarks, just get rid of “->setWatermarkImageOpacity(0)“:

<div class="product_images_exhibit">
	<h2><?php echo $this->__('Product Images') ?></h2>
	<?php $_images = Mage::getModel('catalog/product')->load($_product->getId())->getMediaGalleryImages(); ?>
	<?php if($_images) {?>            
		<?php foreach($_images as $_image) {?>
			<p><img src="<?php echo $this->helper('catalog/image')->init($_product, 'image', $_image->getFile())->constrainOnly(TRUE)->keepAspectRatio(TRUE)->keepFrame(FALSE)->resize(848, null);?>" alt="<?php echo $this->htmlEscape($_image->getLabel());?>" title="<?php echo $this->htmlEscape($_image->getLabel());?>" /></p>
		<?php } ?>
	<?php } ?>
</div>

You would still need to configure watermarks in System -> Configuration -> Design to make this work.

Get Canonical URL of A Product in .PHTML

Canonical URL is a great way to focus SEO power. Without it, search engines would have no idea which particular page among all the similar pages are the most important. Magento, as sophisticated as it can get, does have lots of similar pages regarding the same piece of content such as a product.

When you are adding social buttons, it may not be enough to just add the button and let it detect the current page URL itself. For example, when the user clicks “Edit” of a cart item and gets to the edit page of that item, it’s almost the same as the canonical item page.

If you have social buttons on that page then chances are they won’t be useful at all because they would be promoting the edit page rather than the canonical page. Thus, we need to feed canonical URL rather than the current page URL to them.

How to get the canonical URL of a product programmatically?

It’s as simple as this:

echo $product->getUrlModel()->getUrl($product, array('_ignore_category'=>true));

Make sure you change $product to whatever you are using for the product in your PHTML template.

Page 1 of 41234