Search

shamjascp

This WordPress.com site is the bee's knees

Month

February 2015

What Do You Think of SEO for Magento?

http://www.instantshift.com/2012/06/01/what-do-you-think-of-seo-for-magento/

 

As you may know, SEO stands for “Search engine optimization”. It is the process of getting traffic from “free, organic, editorial or natural” listings on search engines. Enhancing SEO is the best way to improve your website and increase its visibility in search engines.

What Do You Think of SEO for Magento?

According to a statistic of 2009, there were 1,733,993,741 (1.73 billion) internet users in the world. More importantly though, is the fact that approximately 85%, or 1,473,894,680 of them use search engines to find products, services and information. This is one of the reasons SEO Services are strongly impacted on an online store. Besides, search has unrivaled reach amongst internet users. Users are turning up to use the service by choice, a much better option of lead generation than sending unwanted emails. In addition, websites on top of the search engines are given a great deal of credibility and trusted by those finding them, your potential customers. Not only that though, the traffic is unlimited because you aren’t paying for every visitor that clicks your listing.

Another benefit of SEO is the lasting effect that comes with organic search engine rankings. Should you stop using an SEO Service your listing will not immediately vanish as it would should your pay per click budget run out? Implemented correctly an SEO Campaign can maximize the amount of traffic and qualified leads being delivered to your website. An SEO campaign should also be affordable for the results achieved.

We have recently adhered to Magento for a large number of reasons like: full-featured solutions, great effects on sales… for e-commerce. In the transition, however we realized one of challenges of Magento must be Search Engine Optimization. Through some research, experimentation, a few small changes and redesigning, we were able to improve Magento’s out of the box SEO and get back on Google’s good side.

According to our recent report, SEO plays the most important to boost traffic of a Magento store. You will be surprised by the following facts:

  • There are nearly 5 billion Internet searches per month and over 130 million unique searchers.
  • 85% of all Internet traffic is generated through search engines.
  • 90% of Internet users do not go past the top 30 search engine results. They will type something else in the search box if they can’t find a relevant site.

And more important:

  • 75% of Internet users have the intention of purchasing a product or service when using search engines.
  • There are around 130 extensions released to improve Magento stores. They are listed onmagento extension marketplace. It can be seen that, the number of SEO tool makes up nearly 50% of Marketing tools in Magento.

SEO IN MAGENTO?

Magento is one of the most search engine friendly e-commerce applications. It is so easy to the Search Engine Optimization for Magento. You just need to log in backend and go to System > Configuration > Web > Search Engines Optimization:

instantShift - SEO in Magento

In the URL Options it is recommended to turn off the Add Store Code to Urls function (it is set to No by default).

Additionally, the Magento installation set the default page title to Magento Commerce. Pick a more descriptive one and change it from the script admin area >System > Configuration > Design > HTML Head. Enter the new one in the Default Title field. It will be used for pages without custom title. If you want your store name to appear in all page titles put it in the Title Suffix field.

instantShift - SEO in Magento

Read the source article here.

BEST SOLUTION TO OPTIMIZE SEO IN MAGENTO STORES?

1. Optimize The URLs

The first important thing is to optimize your URLs. Please always make sure your URLs are too long. It is necessary to keep them only as you need to make them relevant.

For example: Instead of the URL: http://www.yourstore-best-solutions.com/magento-seo-plus-extension.html, http://www.yourstore.com/magento-seo-plus-extension.html is more preferred. All steps of process could be carried out in Magento backend -> System -> Configuration and set the corresponding values for Web, Catalog including Categories Path and Canonical Ling Meta Tag for Categories.

2. Tweak The CMS

You need to tweak your CMS, Product and Category Pay Titles. Page tittles are heavily weighted in a search engines’ view. If you could make it relevant, less than 70 characters and put your most important key words in the beginning of the title, there are about 50% of SEO to your website. Then, how to change the page titles:

  • CMS Pages: your “Page Title” is the Meta Title. The CMS is a great management tool for your business which also allows you to make content revisions. It is important for SEO to especially update content on landing pages with call to actions. Optimizing your content and engaging the customer can sometimes make or break the sale. Now that up optimized the content you can pick a SEF URL Identifier and page title (keep in mind the points under 1.2). Go to the Meta Data tab to write a description for each CMS page that you actually want to rank with. The keywords are not that important so you can keep the keywords empty. The description is all about relevance. The more relevant the more people will not only click on the page but also stay within the website. It is important to state what’s in the page they’re clicking on and that the information grabs their attention. If you don’t use the Meta description, the search engine will find the keyword searched for in your document, and automatically pick a string around that, which gives you a bolded word or two in the results page.
  • Products: Go to Catalog > Manage Products. Click the product you want to edit, click “Meta Information” on the left and edit the “Meta Title” field. You can set the Meta Information for the “Default Values” and for each “Store View”. Note that for the “Meta Title”, this will overwrite the complete page title, including categories but except title prefix/suffix, and not just the product name.

    An important aspect of SEO is optimizing your images. Speed is a very important part of SEO. The faster you page loads the better the experience for the user and the more likely they will stick around to buy your products. In the end, optimizing your images is both good for your sales as well as your customers. It is also important to write relevant alt tags for images and properly name your image files. This can also help increase traffic from the Image search queries such as “Google Images.” This is also important proper alt descriptions for the users that are unable to view your image. By default the images will be renamed to the product title, the same for titles and alt tags. With some extra effort you can set the titles and alt tags for each product image. To change the default you can set the titles and alt tags for each individual product by going to “Images” of the Product Information where you can then set the label for each product image. This will allow you to update the alt and title tag and you can do this for each specified Store View as well.

  • Categories: Go to Catalog > Categories. Click the category you want to edit, and edit the “Page Title” field. It is important to disable the “use categories path for product URL’s” as No! Although Magento grants you the ability to add the name of categories to the path for each product URL it often creates duplicate content which is not good for SEO. To disable this go to System— Configuration—Catalog —Search Engine Optimization— and set “Use categories path for product URL’s to “no”. Now you can change the details for each category by going to Catalog—Manage Categories. The most important fields to complete are Meta Description, Page Title, and URL Key. With Meta Description it is important to put an attractive description here; Keep in mind that people will see the description in the result listings of search engines. With Page Title it is important keep this empty to use the category name including parents’ categories. When you customize it, the title will be exactly like your input, without the parent category. Last but not least, with the URL Key you should try to keep a short but keyword rich URL. Removing stop words like “the”, “and”, “for” etc. is usually a good idea. Also note that you can set this only for all store views, for a multi-language store you should keep it language independent. For each store view you can specify the Name, Description, Page Title and Meta data. This is a great feature for multi- language stores.

3. Straightforward Navigation Menu

The third way is design a straightforward Navigation Menu. Big data-rich dropdown menus and footers are in style but they bring a drawback. Too much information makes the rest of your pages look like duplicate content. If your navigation menu makes up 70% of the content on most pages, search engines think all of your pages only have 30% of original content, which hurts your ranking.

Moreover, too many links in the header or footer can skyrocket your link count on every page, breaking the general accepted 100 links per page limit and your site will look like a link farm to a crawler. You’re also spreading link juice too thin, passing too little to each link instead of a concentrated amount to a few links. Take some hints from Apple.com, who has one of the most simple navigation menus around.

4. Optimize The Page Load Speed

Get it to Run Fast Without Switching Hosts: it is undeniable that Magento is unbearably slow, and that is no good for SEO. Luckily, speeding it up is a 1 step solution. Bring your pages load time from 2, 3 and 4 seconds down to less than 100 milliseconds will bring more search and bargain accordingly.

Also, there are additional ways to better optimize your Magento SEO as the following:

  • Magento default Meta tags optimization: Go to Configuration > Design > HTML Head and fill in the Default Title and Default Description fields. This will ensure that new pages have a generic but at least well optimized title and description in case you forget to enter the specific page title and description.
  • Create Google Sitemap (sitemap.xml) in Magento. Magento has a great Google XML sitemap generation tool (System > Configuration > Google Sitemap) which allows you to customize prettily much anything including different frequency and priority value for different types of pages. For example, you may want to assign to category pages frequency ‘daily’ and priority of 0.8, but you may want to set those to ‘weekly’ and ‘0.5’ on all content pages.

The tool also lets you configure sitemap generation settings, including how often the sitemap.xml should be updated, at what time during the day and who’s the main point of contact if something goes wrong. Once configured, all you need to do is go to Catalog > Google Sitemap and generate a new sitemap.xml file.

  • Add Google Webmaster Tools verification tag to Magento. You need to add Google Webmaster Tools verification Meta tag to Magento website without having to involve developers in such smak and easy task? No problem. Go to System > Configuration > Design > HTML Head and paste your Webmaster Tools verification code in Miscellaneous scripts section. Complete!
  • Site maps allow an easier understanding of where your content is for both search engines as well as users. To create sitemap in Magento Simply go to Catalog—Google Sitemap—Add Sitemap—Chose a File Name—Chose Path and Store View—Press Save and Generate. Put Sitemap:http://domain.com/sitemap.xml in your robots.txt file. Make sure you update your site map as you update your inventory.
  • Set up Magento Google Base feed: this is definitely one of the optional Magento SEO tips but you may as well as set up the Magento Google. Base feed straight way as the feed’s history to be one of the ranking factors for Google Shopping listings. I created a detailed step by step guide on How to successfully Set UpMagento Google Base Feed.
  • Aim for speed: Speed is the most noteworthy factor that directly contributes to visitor’s traffic. The two notable things that can be done to enhance your Magento install’s speed are:
  • Facilitate caching. Go to System=> Cache Management and enable the caching features.
  • You can significantly increase Magento’s speed by using PHPopcode cache and MySQL.

5. Optimize The Template

One thing improving SEO of your Magento store must be Magento Template Optimization. The guide below will show you the effective ways to optimize Magento template.

  • Optimized Blank Template: The default Magento coats like “Modern Theme”, “Default Theme”, and “Blue Skin” do not perform well in the use of headings. From the view of SEO there is a lot of scope for development. A Blank Magento SEO Theme, depending on the core Magento Blank Theme is developed for your ease.
  • Headings: The default logo is an h1, and this should only appear on the front page, apart from this page, all other pages should be no more than an h3. The significant factor is to obtain the title of the content in an h1 tag. For example a category page should have the category name and for a product page it should have the product name. Next to this you should clean up the excess usage of headings.
  • It is recommended to eliminate the usage of header in the side columns. You can also make the text pertinent to the store (for example: include keywords). There is no basis for adding “static” and keyword less titles with an h4. For example it is good to alter all the h4 tags in div class=”head” to strong tags. This is the best time for content optimization. Place the category name in an h1 and the product names in an h3 at the category pages and set the product name in an h1 on the On product pages.

6. Code Properly

Because the templates do not contain clean optimized code, it would be beneficial to move the JavaScript and CSS to an external file. This way a user can cache the files on the first load and search engines will not waste time downloading them. Aiming for speed is very important for gaining more traffic. It is vital for the shop to load quickly. Here are a few ways in which you can increase the speed of your Magento install. First, enable caching. Go to System— Cache Management and enable all caching features. Second, it is important to have a good host and server configuration. With MySQL and PHP opcode cache you can improve the speed of Magento significantly. It is important to limit the number of external files. For each file you make people download, their browser has to create another connection to the web server. It is good for SEO to reduce the number of external files and combine several external files in to one. By default Magento already combine the majority of JavaScript files into one file except for style sheets. By the default template there are 6 style sheets. All of the content style sheets can be combined into one except for the print.css file. It is good to compress and cache both your java script and style sheet files.

7. Eliminating Duplicate Content

Once you have optimized the basic configuration and content updates for SEO you may be left with extra duplicate content. For example the following is a demonstration of duplicate content:

domain.com/product.html
domain.com/category1/product.html
domain.com/catalog/product/view/id/1/
domain.com/catalog/product/view/id/1/category/1/

One problem is that the pages are like the product review pages with almost the same content. Another problem is that the categories get a load of duplicate content with layered navigation and the sorting options. This means that a product may be available on 4 pages at least next to the page where it should be available. The key is to get rid of duplicate content pools but still allow them to be speared but not indexed by fixing the sorting options and layered navigation for categories. Now the search engine will follow all links on these pages but it won’t show those pages in the index. It is now important to “No follow” all unnecessary links. It is important to stop linking to your login, checkout, RSS feeds, Layered Navigation, or any other non-content page existing on your site.

If you want to suggest the preferred version of the URL for each page you can install the Canonical URL’s for Magento Module to help search engines understand the duplicate content of your pages.

Conclusion

In conclusion, SEO is very topical at the moment. Making these changes, along with other good SEO practices, will significantly optimize your search rankings and get you relevant, organic traffic as a result. These Magento Search Engine Optimization tips will help in optimizing your Magento website.

How To Show Most Viewed & Best Selling Products In Magento Store

http://www.magikcommerce.com/blog/how-to-show-most-viewed-best-selling-products-in-magento-store/

Lately, we have noticed that many Magento store owners started asking us how to show most viewed products or best selling products on their store’s home page or some other places in their store. Unfortunately, there is nothing like these feature pre built in Magento core so you have to tweak and write some lines of code to make it work.

Display Most Viewed Products

Step 1: Create a fileapp/code/local/Mage/Catalog/Block/Product/Mostviewed.php and add the following lines of code in it

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Mage_Catalog_Block_Product_Mostviewed extends Mage_Catalog_Block_Product_Abstract{
    public function __construct(){
        parent::__construct();
        $storeId    = Mage::app()->getStore()->getId();
        $products = Mage::getResourceModel('reports/product_collection')
            ->addOrderedQty()
            ->addAttributeToSelect('*')
            ->addAttributeToSelect(array('name', 'price', 'small_image'))
            ->setStoreId($storeId)
            ->addStoreFilter($storeId)
            ->addViewsCount();
        Mage::getSingleton('catalog/product_status')->addVisibleFilterToCollection($products);
        Mage::getSingleton('catalog/product_visibility')->addVisibleInCatalogFilterToCollection($products);
 
        $products->setPageSize(5)->setCurPage(1);
        $this->setProductCollection($products);
    }
}

Step 2: Create a fileapp/design/frontend/default/YourTheme/template/catalog/product/mostviewed.phtmland add the following lines of code in it

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<?php if (($_products = $this->getProductCollection()) && $_products->getSize()): ?>
<div class=" most_viewed">
<div class="mv_title"><?php echo $this->__('These Products Are Popular Right Now!') ?></div>
<?php $_collectionSize = 5;//count($_products->getItems()); echo $_collectionSize; ?>
<ul class="products-grid" id="products-grid-table">
<?php $i=1; foreach ($_products->getItems() as $_product): ?>
    <li id="td_<?php echo $i;?>" <?php if($i%5==0 or $i==$_collectionSize){echo 'class="last"';} ?> >
        <div id="cont_<?php echo $i;?>">        
            <a class="product-image" href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $this->htmlEscape($this->getImageLabel($_product, 'small_image')) ?>">
                <img src="<?php echo $this->helper('catalog/image')->init($_product, 'small_image')->resize(135); ?>" width="135" height="135" alt="<?php echo $this->htmlEscape($this->getImageLabel($_product, 'small_image')) ?>" title="<?php echo $this->htmlEscape($this->getImageLabel($_product, 'small_image')) ?>" />
            </a>
            <h3 class="product-name"><a href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $this->htmlEscape($_product->getName()) ?>"><?php echo $this->htmlEscape($_product->getName()) ?></a></h3>
            <div class="a-center">                        
                <?php if($_product->getRatingSummary()): ?>
                    <?php echo $this->getReviewsSummaryHtml($_product, 'short') ?>
			    <?php endif; ?>
                <?php echo $this->getPriceHtml($_product, true) ?>
                <?php if($_product->isSaleable()): ?>
                    <button class="button" onclick="setLocation('<?php echo $this->getAddToCartUrl($_product) ?>')"><span><span><span><?php echo $this->__('Add to Cart') ?></span></span></span></button>
                    <div class="clear"></div>
                <?php else: ?>
                    <p class="availability"><span class="out-of-stock"><?php echo $this->__('Out of stock') ?></span></p>
                    <div class="clear"></div>
                <?php endif; ?>
                <ul class="add-to-links">
                    <?php if ($this->helper('wishlist')->isAllow()) : ?>
                    <li><a href="<?php echo $this->helper('wishlist')->getAddUrl($_product) ?>"><?php echo $this->__('Add to Wishlist') ?></a></li>
                    <?php endif; ?>
                    <?php if($_compareUrl=$this->getAddToCompareUrl($_product)): ?>
                    <li class="last"><span class="separator">|</span> <a href="<?php echo $_compareUrl ?>"><?php echo $this->__('Add to Compare') ?></a></li>
                    <?php endif; ?>
                </ul>
            </div>
        </div>
    </li>
<?php $i++; endforeach; $kol = $_collectionSize; ?>
</ul>
</div>
<?php endif; ?>

Step 3: Now, we have the code in place which will fetch the most viewed products on call. Still, we need to add a block to show most viewed products in a desired location

1
{{block type="catalog/product_mostviewed" template="catalog/product/mostviewed.phtml"}}

Display Best Selling Products

Step 1: Create a fileapp/code/local/Mage/Catalog/Block/Product/Bestseller.php and the following lines of code in it

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Mage_Catalog_Block_Product_Bestseller extends Mage_Catalog_Block_Product_Abstract{
    public function __construct(){
        parent::__construct();
        $storeId = Mage::app()->getStore()->getId();
        $products = Mage::getResourceModel('reports/product_collection')
            ->addOrderedQty()
            ->addAttributeToSelect('*')
            ->addAttributeToSelect(array('name', 'price', 'small_image'))
            ->setStoreId($storeId)
            ->addStoreFilter($storeId)
            ->setOrder('ordered_qty', 'desc'); // most best sellers on top
        Mage::getSingleton('catalog/product_status')->addVisibleFilterToCollection($products);
        Mage::getSingleton('catalog/product_visibility')->addVisibleInCatalogFilterToCollection($products);
 
        $products->setPageSize(3)->setCurPage(1);
        $this->setProductCollection($products);
    }
}

Step 2: Create a fileapp/design/frontend/default/YourTheme/template/catalog/product/bestseller.phtmlfile and add the following lines of code in it

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
<?php if (($_products = $this->getProductCollection()) && $_products->getSize()): ?>
<div class="page-title">
    <h2><?php echo $this->__('Best Seller Products') ?></h2>
</div>
<?php $_collectionSize = count($_products->getItems()) ?>
<table class="products-grid" id="products-grid-table">
<?php $i=1; foreach ($_products->getItems() as $_product): ?>
    <?php if ($i%1!==0): ?>
    <tr>
    <?php endif ?>
        <td id="td_<?php echo $i;?>" <?php if($i%3==0 or $i==$_collectionSize){echo 'class="last"';} ?> >
        <?php contentBlock('top') ?>
        <div id="cont_<?php echo $i;?>">
            <h3 class="product-name"><a href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $this->htmlEscape($_product->getName()) ?>"><?php echo $this->htmlEscape($_product->getName()) ?></a></h3>
            <a class="product-image" href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $this->htmlEscape($this->getImageLabel($_product, 'small_image')) ?>">
                <img src="<?php echo $this->helper('catalog/image')->init($_product, 'small_image')->resize(122, 109); ?>" width="122" height="109" alt="<?php echo $this->htmlEscape($this->getImageLabel($_product, 'small_image')) ?>" title="<?php echo $this->htmlEscape($this->getImageLabel($_product, 'small_image')) ?>" />
            </a>
            <div class="a-center">                        
                <?php if($_product->getRatingSummary()): ?>
                    <?php echo $this->getReviewsSummaryHtml($_product, 'short') ?>
                <?php endif; ?>
                <?php echo $this->getPriceHtml($_product, true) ?>
                <?php if($_product->isSaleable()): ?>
                    <button class="button" onclick="setLocation('<?php echo $this->getAddToCartUrl($_product) ?>')"><span><span><span><?php echo $this->__('Add to Cart') ?></span></span></span></button>
                    <div class="clear"></div>
                <?php else: ?>
                    <p class="availability"><span class="out-of-stock"><?php echo $this->__('Out of stock') ?></span></p>
                    <div class="clear"></div>
                <?php endif; ?>
                <ul class="add-to-links">
                    <?php if ($this->helper('wishlist')->isAllow()) : ?>
                        <li><a href="<?php echo $this->helper('wishlist')->getAddUrl($_product) ?>"><?php echo $this->__('Add to Wishlist') ?></a></li>
                    <?php endif; ?>
                    <?php if($_compareUrl=$this->getAddToCompareUrl($_product)): ?>
                        <li class="last"><span class="separator">|</span> <a href="<?php echo $_compareUrl ?>"><?php echo $this->__('Add to Compare') ?></a></li>
                    <?php endif; ?>
                </ul>
                <?php if($_product->getevent_date()) {echo $_product->getevent_date();} ?>
            </div>
        </div>
    </td>
    <?php if ($i%3==0 or $i==$_collectionSize): ?>
   </tr>
    <?php endif ?>
  <?php $i++; endforeach; $kol = $_collectionSize; ?>
</table>
<?php endif; ?>

Step 3: This above files will create a list of best selling products which can be shown anywhere on your Magento store. All you have to do is place the following line of code block in your template to show the best selling products.

1
{{block type="catalog/product_bestseller" template="catalog/product/bestseller.phtml"}}

Sweet, now we are able to show best selling products and most viewed products anywhere in our Magento store. If you run into any problem implementing the code, please feel free to comment and let me know. Subscribe our RSS To receive latest Magento development updates.

Google map Styles

https://snazzymaps.com/style/15/subtle-grayscale

'Snazzy Maps

<!DOCTYPE html>
<html>
<head>
<title>Snazzy Maps Super Simple Example</title>

<style type=”text/css”>
/* Set a size for our map container, the Google Map will take up 100% of this container */
#map {
width: 750px;
height: 500px;
}
</style>

<!–
You need to include this script on any page that has a Google Map.
When using Google Maps on your own site you MUST signup for your own API key at:
https://developers.google.com/maps/documentation/javascript/tutorial#api_key
After your sign up replace the key in the URL below or paste in the new script tag that Google provides.
–>
<script type=”text/javascript” src=”https://maps.googleapis.com/maps/api/js?key=AIzaSyASm3CwaK9qtcZEWYa-iQwHaGi3gcosAJc&sensor=false”></script&gt;

<script type=”text/javascript”>
// When the window has finished loading create our google map below
google.maps.event.addDomListener(window, ‘load’, init);

function init() {
// Basic options for a simple Google Map
// For more options see: https://developers.google.com/maps/documentation/javascript/reference#MapOptions
var mapOptions = {
// How zoomed in you want the map to start at (always required)
zoom: 11,

// The latitude and longitude to center the map (always required)
center: new google.maps.LatLng(40.6700, -73.9400), // New York

// How you would like to style the map.
// This is where you would paste any style found on Snazzy Maps.
styles: [{“featureType”:”landscape”,”stylers”:[{“saturation”:-100},{“lightness”:65},{“visibility”:”on”}]},{“featureType”:”poi”,”stylers”:[{“saturation”:-100},{“lightness”:51},{“visibility”:”simplified”}]},{“featureType”:”road.highway”,”stylers”:[{“saturation”:-100},{“visibility”:”simplified”}]},{“featureType”:”road.arterial”,”stylers”:[{“saturation”:-100},{“lightness”:30},{“visibility”:”on”}]},{“featureType”:”road.local”,”stylers”:[{“saturation”:-100},{“lightness”:40},{“visibility”:”on”}]},{“featureType”:”transit”,”stylers”:[{“saturation”:-100},{“visibility”:”simplified”}]},{“featureType”:”administrative.province”,”stylers”:[{“visibility”:”off”}]},{“featureType”:”water”,”elementType”:”labels”,”stylers”:[{“visibility”:”on”},{“lightness”:-25},{“saturation”:-100}]},{“featureType”:”water”,”elementType”:”geometry”,”stylers”:[{“hue”:”#ffff00″},{“lightness”:-25},{“saturation”:-97}]}]
};

// Get the HTML DOM element that will contain your map
// We are using a div with id=”map” seen below in the <body>
var mapElement = document.getElementById(‘map’);

// Create the Google Map using our element and options defined above
var map = new google.maps.Map(mapElement, mapOptions);

// Let’s also add a marker while we’re at it
var marker = new google.maps.Marker({
position: new google.maps.LatLng(40.6700, -73.9400),
map: map,
title: ‘Snazzy!’
});
}
</script>
</head>

Magento: Getting product attributes values and labels

http://www.sharpdotinc.com/magento-getting-product-attributes-values-and-labels/

Magento: Getting product attributes values and labels

I have found that it is very useful to be able to get attributes from the system and use them in places other than a products category page. I always forget the exact syntax to use so, this is going to be my unofficial cheat sheet.

This is how to get a drop down lists options. I don’t think it will work for a mulit-select attribute. I stick the value/label pairs into an array to use how I please.

$attribute = Mage::getModel(‘eav/config’)->getAttribute(‘catalog_product’, ‘attribute_id’);
foreach ( $attribute->getSource()->getAllOptions(true, true) as $option){
$attributeArray[$option['value']] = $option['label'];
}

I had a trickier time getting values for a multi-select attribute. I don’t think that this is the best method, but it is one that worked for me. First the multi-select attribute must be set to be used in the advanced search. You can set this in the manage attributes area.

$attributes = Mage::getModel(‘catalogsearch/advanced’)->getAttributes();
$attributeArray=array();
foreach($attributes as $a){
if($a->getAttributeCode() == ‘desired_attribute_code’){
foreach($a->getSource()->getAllOptions(false) as $option){
$attributeArray[$option['value']] = $option['label'];
}
}
}

Here is a better way to get the multi-select attribute values.

$attributeId = Mage::getResourceModel(‘eav/entity_attribute’)
->getIdByCode(‘catalog_product’,’attribute_code_here’);
$attribute = Mage::getModel(‘catalog/resource_eav_attribute’)->load($attributeId);
$attributeOptions = $attribute ->getSource()->getAllOptions();

If you only need to retrieve a value for a product you can try this way

//Referenced from /app/code/core/Mage/Eav/Model/Config/php @ line 443
$_product->getResource()->getAttribute(‘club_type’)->getFrontend()->getValue($_product)

I added this code snip it below to possibly answer a question that was posted. The code below will get an attribure collection. Set {entityType} to 4 to get attributes for products. You can remove the “setCodeFilters” line if you want to get all the attributes. To get anything really useful you will probably need to get the resulting attribute ids and do someting with them, like use them in a filter for the products collection or something.

//
$attributesInfo = Mage::getResourceModel(‘eav/entity_attribute_collection’)
->setEntityTypeFilter({entityType})
->setCodeFilter($attributes)
->addSetInfo()
->getData();

Entity Type Id’s
$entityType is an integer id for what type of entity the attribute is associated to. If you look at the “eav_attribute” table you will see that each attribute has an entity_type_id.
1 = Customer Entity
2 = Shipping Entity (I believe)
3 = Category Entity
4 = Product Entity

The Following code was added to answer a question in the replies:
To make a product attribute avaliable when getting a product collection(such as on a category page or search results page) you can add some code the a config.xml file that instructs Magento to load allways the attribute when a product collection is loaded.

How to add an  attribute to be loaded whenever a product collection is loaded:
This can go in any config.xml file. I would recommend putting it in a custom module rather than one from the core code. Just replace “attribute_name” with the attribute code of the attribute you are trying to add.


How to get Only the Attribute Values that have been used on products

The Code below will get the attribute values that have been used on the products in the product collection.
This may not be the best way to do this, but it is what I came up with.

//First get the attribute id
$audienceAttributeId = Mage::getResourceModel(‘eav/entity_attribute’)->getIdByCode(‘catalog_product’,’session_audience’);
//Now Load the attribute
$audienceAttribute = Mage::getModel(‘catalog/resource_eav_attribute’)->load($audienceAttributeId);

//Now get the product collection that you want to use to fine the attributes values for.
//I wanted the attribute values for only grouped products. You could add category filters and such
$productCollection = Mage::getModel(‘catalog/product’)->getCollection()
->addStoreFilter(Mage::app()->getStore())
->addAttributeToSelect(‘session_audience’)
->addAttributeToSort(‘session_audience’, ‘asc’)
->addAttributeToFilter(‘type_id’, array(‘eq’ => ‘grouped’));

//Now get the product ids for the collection
$productCollectionIds = $productCollection ->getAllIds();

//Now we query the data base to get the attribute values for the given product ids.
//NOTE that I am selecting from the catalog_product_entity_varchar table because this is the type of attribute I was using.
$read = Mage::getSingleton(‘core/resource’)->getConnection(‘core_read’);
$select = $read->select();
$select->from(‘catalog_product_entity_varchar’)
->where(‘attribute_id = ?’, $audienceAttributeId)
->where(‘entity_id IN (?)’, $productCollectionIds );

//print_r($select->__toString());die();

//Now get the ids for the attribute values.
$result = $read->query($select);
$attributeOptionIds = array();
while($row = $result->fetch()){
$attributeOptionIds = array_merge($attributeOptionIds, explode(‘,’, $row['value']));
}
array_unique($attributeOptionIds);
//print_r($audienceOptions);die();

//Now get the actual values for the Ids as a Collection and do something with the values.
$filteredAudienceCollection = Mage::getResourceModel(‘eav/entity_attribute_option_collection’)
->setPositionOrder(‘asc’)
->setAttributeFilter($audienceAttributeId)
->setStoreFilter($audienceAttribute->getStoreId())
->addFieldToFilter(‘main_table.option_id’, array(‘in’ => $attributeOptionIds))
->load();

About The Author


94 Comments

deXX » 22 Apr 2009 » Reply

You are my hero today! :D
Thanks a lot!

weekend » 18 Jun 2009 » Reply

wow! the 2nd method works fine!!

I use this to check if attribute exits too:

if (!$id = $eav_entity_setup->getAttribute($entity_type_id, $code, ‘attribute_id’)) {
return false;
}

thanks!

Sasha » 28 Jul 2009 » Reply

Oh! Thank you ! You save my time.

Nick Mallare » 30 Aug 2009 » Reply

Thank you! I have been trying to find this code for the last few days.

Nick

igor » 7 Sep 2009 » Reply

Thanks, do you have any idea how to get attributes by attribute_id which only relate to existing products in DB.
I’ll try to display it as filters (so if no products have assigned attribute, attribute not display).

mdost » 7 Sep 2009 » Reply

Added reference to code that gets a collection of attributes.

fg » 17 Sep 2009 » Reply

thanks dude ;)

Phil » 21 Sep 2009 » Reply

It would be helpful if you could post a further description of what $entityType is (from the last example) and why 4 is the value to use for products.

mdost » 22 Sep 2009 » Reply

$entityType is an integer id for what type of entity the attribute is associated to. If you look at the “eav_attribute” table you will see that each attribute has an entity_type_id.
1 = Customer Entity
2 = Shipping Entity (I believe)
3 = Category Entity
4 = Product Entity

and so on. THese four ids are the ones that you will commonly use.

Kamil P » 12 Nov 2009 » Reply

thanks very much!
I used this: $_product->getResource()->getAttribute(‘club_type’)->getFrontend()->getValue($_product)

but for total noobs (like myself) it is worth to mention that you need to add “echo” in front of the line to actually display the value of the attribute: so in your code you will have:

getResource()->getAttribute(‘name_of_the_attribute’)->getFrontend()->getValue($_product) ?>

hope this helps someone totally lost,
Kamil

benz001 » 25 Nov 2009 » Reply

For the multi-select, if you’re within a Mage_Catalog_Block_Product_View template (ie view.phtml) then you don’t need the advanced search visibility to be set or referenced, this works as well:

$attributes = $_product->getAttributes();
$attributeArray=array();
foreach($attributes as $a){
if($a->getAttributeCode() == 'your_code_here'){
foreach($a->getSource()->getAllOptions(false) as $option){
$attributeArray[$option['value']] = $option['label'];
}
}
}

J » 29 Dec 2009 » Reply

Hi
thanks for this, which is pretty clear, but I dont get anything when I code this:

public function test_ProductData_DefaultProductSize_ShouldBeT1()
{
// Actors
$_product;
$optionCode ="size";
$expectedValue = "T1";
$actualValue = "QUELLE EST CETTE TAILLE";
$productId = "4b38dffad30c6";

// Activities
$_product= null;
$_product = new Mage_Catalog_Model_Product();
$_product = Mage::getModel(‘catalog/product’)->load($productId);

$actualValue = $_product->getResource()
->getAttribute($optionCode)
->getFrontend()
->getValue($_product);

// Asserts
$this->assertEquals($expectedValue, $actualValue, "ASSERT FAILURE: attribute $optionCode is wrong.");
}

any idea of what I could have missed?

J » 29 Dec 2009 » Reply

I get this display:

There was 1 failure:

1) Moz_Product_ProductTestAttributes::test_ProductData_DefaultProductSize_ShouldBeT1
ASSERT FAILURE: attribute size is wrong.
Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ @@
-T1
+No

Mike D » 29 Dec 2009 » Reply

@J: I believe you are loading the product incorrectly. After you load the product, does “$_product” have an ID “$_product->getId()”?

J » 30 Dec 2009 » Reply

Thanks Mike D,
I rewrote the get of the product as :

public static function GetProductFromSku($skuId)
{
$products = Mage::getModel('catalog/product')->getCollection()
->addAttributeToFilter('sku',$skuId)
->load();

if (0 === count($products)) {
throw new Exception("Error: Product $skuId not found");
}
$product = null;
foreach($products as $p) {
$product = $p;
break;
}
if(null === $product) {
throw new Exception("Error: Product $skuId not in result collection");
}
return $product;
}

and then my test is:


public function test_ProductData_DefaultProductSize_ShouldBeT1()
{
// Actors
$_product= null;
$optionCode ="size";
$expectedValue = "T1";
$actualValue = "QUELLE EST CETTE TAILLE";
$productId = "cdn0001";

// Activities
$_product = new Mage_Catalog_Model_Product();
$_product = common_ProductData::GetProductFromSku($productId);//Mage::getModel(‘catalog/product’)->load($productId);

$actualValue = $_product->getResource()->getAttribute($optionCode)->getFrontend()->getValue($_product);

// Asserts
$this->assertNotNull($_product->getId(), “ASSERT FAILURE: Product id should be set !”);
$this->assertTrue($_product->getId() > 0, “ASSERT FAILURE: Product id is “.$_product->getId());
$this->assertEquals(“1”, $_product[‘stock_item’][‘is_in_stock’], “ASSERT FAILURE: Product should be In Stock”);

$this->assertEquals($expectedValue, $actualValue, "ASSERT FAILURE: attribute '$optionCode' is wrong.");
}

But the result is still:

There was 1 failure:

1) Moz_Product_ProductTestAttributes::test_ProductData_DefaultProductSize_ShouldBeT1
ASSERT FAILURE: attribute ‘size’ is wrong.
Failed asserting that two strings are equal.
— Expected
+++ Actual
@@ @@
-T1
+No

C:svnmoztrunktestsintegrationMozProductProductTestAttributes.php:27

FAILURES!
Tests: 1, Assertions: 5, Failures: 1.

When I parse the attributes with a foreach ($_product->getAttributes() as $attribute)

I can see the “Size”, but it is the label. How to get the value for the $_product ?

Riccardo » 18 Jan 2010 » Reply

I’m trying to retrieve attributes name (multilanguage) in the catalog list (when the products are listed in categories), is it possible using this method?

Because “$attribute->getSource()->getAllOptions(true, true)” returns me an empty array of this type:
“Array ( [0] => Array ( [label] => [value] => ) )”

Am I doing something wrong?

Mike D » 18 Jan 2010 » Reply

What type of attribute is “multilanguage”?

1. I am assuming you created it?
2. Is it a text field, drop-down, …?

Are you just trying to display it for each product on the product list?

One way to do this would be to add that attribute to a config file so it always loads when Magento grabs the product collection. I have added sample code to the end of the post that demonstrates this.

Mukesh » 19 Jan 2010 » Reply

Here is the solution to get attribute label for multilanguage site:

$attributeLabel = $_product->getResource()->getAttribute(‘YOUR_ATTRIBUTE_CODE’)->getFrontendLabel();
$translationArray = Mage::app()->getTranslator()->getResource()->getTranslationArray();
echo $translationArray[“Mage_Catalog::”.$attributeLabel];

Hope this helps.

Bhavesh Dave » 19 Jan 2010 » Reply

hay any one help me to list out all options and its values of particular product…

Mike D » 20 Jan 2010 » Reply

@Bhavesh Dave: Are you trying to print all options for a particular attribute for a product or all attributes for a product?

if $product is your product then you list attributes by
$product->getAttributeName();

To see all the attributes available you can do print_r($product);

Does this help?

Oliver Schörwerth » 10 Feb 2010 » Reply

THANK YOU!
You saved me a lot of time!

Now i can go home :)

Tuppi Sau » 31 Mar 2010 » Reply

Nice Posts, but I have a different problem, I would like to add a foreign key to the product table. i.e. I wanted to filter the product according to the administrator who added the product from the administrator’s panel. i.e. I want to keep track of the products according to administrator’s role and permission. Is it possible to do so. If yes, how? Please respond. Thanx.

Mike D » 31 Mar 2010 » Reply

@tuppi Sau: What you want to do sounds reasonable. You would need to create a module that adds the nessary attributes to the product then create an observer or override the methods for product create/update. If you are a beginner you might want to pay someone to build this.

Here are a few articles that should get you started.
For installing custom attributes with a module

To add the new attributes to the product grid you will more than likely need to override the block and template files for this.

MagMonster » 27 Apr 2010 » Reply

Is it possible to get all (non core) attributes in the magento shop? I need this to create attribute sets programatically.

Mike D » 27 Apr 2010 » Reply

I don’t believe there is a method that will do exactly that. I am not sure why you would need to do that. If you are creating an attribute set then you should know what attributes you want to add to it so just use addAttributeToFilter(), for each attribute you want. Or explain what you are trying to do a little better.

Gleb » 26 May 2010 » Reply

Hello,
I’m looking for a method to show all possible attributes and their values for some product, even those, which are not in stock. I have to show possible sizes and colors to the customer..
Any ideas how to add filtering by product ID to “get all attributes/values”?
Thanks.

Mike D » 26 May 2010 » Reply

This might not be the easiest way, but what if you make an array of attributes with the key of the array being the attribute_code and the value being what type of attribute it is(select, multi-select, text field, ect.) Then do a foreach loop with the array and check to see if the current product has that attribute then if it does have the attribute, check to see which type of output it has(select, multi-select, text field, ect.) and use the appropriate code from the example above to retrieve the values.

I cant remember if there is a method that will just get all the attributes for a product.

Gleb » 26 May 2010 » Reply

Thank you, Mike.
I also found another variant, looks like it works:
$possibleAttributes = $product->getTypeInstance(true)->getConfigurableAttributesAsArray($product);

Anita » 5 Jun 2010 » Reply

Thanks, it worked and now can show the attribute option value in product listing.

Andrea » 29 Jun 2010 » Reply

Thanks Mike, with your help now I see custom attributes on my landing pages!

Giannis » 2 Aug 2010 » Reply

Thanks!!!

Peter » 4 Sep 2010 » Reply

HI i have a Problem getting the Options of an Multiselect Attribute… I created the multiselect Attribute in the Adminpanel with two options. Now i tried this:

$attribute = Mage::getModel(‘eav/entity_attribute’);
$attribute->loadByCode(‘catalog_product’, “products_author_unique”);
$options = $attribute->getSource()->getAllOptions(false);

but “$attribute->getSource()” throws an error:
Fatal error: Call to a member function setAttribute() on a non-object in C:xampphtdocsMagentoappcodecoreMageEavModelEntityAttributeAbstract.php on line 374

a dump of my $attribute looks like this:
Mage_Eav_Model_Entity_Attribute Object
(
[_eventPrefix:protected] => eav_entity_attribute
[_eventObject:protected] => attribute
[_cacheTag:protected] => EAV_ATTRIBUTE
[_name:protected] =>
[_entity:protected] =>
[_backend:protected] =>
[_frontend:protected] =>
[_source:protected] =>
[_attributeIdCache:protected] => Array
(
)

[_dataTable:protected] =>
[_resourceName:protected] => eav/entity_attribute
[_resource:protected] =>
[_resourceCollectionName:protected] => eav/entity_attribute_collection
[_dataSaveAllowed:protected] => 1
[_isObjectNew:protected] =>
[_data:protected] => Array
(
[attribute_id] => 577
[entity_type_id] => 4
[attribute_code] => products_author_unique
[attribute_model] =>
[backend_model] => eav/entity_attribute_backend_array
[backend_type] => varchar
[backend_table] =>
[frontend_model] =>
[frontend_input] => multiselect
[frontend_label] => products_author_unique
[frontend_class] =>
[source_model] =>
[is_required] => 0
[is_user_defined] => 1
[default_value] => 6
[is_unique] => 0
[note] =>
[frontend_input_renderer] =>
[is_global] => 0
[is_visible] => 1
[is_searchable] => 1
[is_filterable] => 1
[is_comparable] => 1
[is_visible_on_front] => 0
[is_html_allowed_on_front] => 1
[is_used_for_price_rules] => 0
[is_filterable_in_search] => 1
[used_in_product_listing] => 1
[used_for_sort_by] => 0
[is_configurable] => 0
[apply_to] =>
[is_visible_in_advanced_search] => 1
[position] => 0
[is_wysiwyg_enabled] => 0
[is_used_for_promo_rules] => 0
)

[_hasDataChanges:protected] => 1
[_origData:protected] =>
[_idFieldName:protected] => attribute_id
[_isDeleted:protected] =>
)

Mike D » 5 Sep 2010 » Reply

@Peter: Doesn’t look like you followed the directions for a MultiSelect Attribute.

Read Paragraph 3.

I had a trickier time getting values for a multi-select attribute. I don’t….

Horatiu Taina » 16 Sep 2010 » Reply

Hi!

How can I get the attribute set id of a product?

I bet it’s simple, but I just can’t figure it out!

I have:

$product = Mage::registry(‘product’);

And what do I do next?

echo $product->getResource()->… ?

Thanks in advance,
HT

Horatiu Taina » 16 Sep 2010 » Reply

I figured it out by making a ReflectionClass and displaying it’s methods.

$product->getAttributeSetId()

It was pretty simple!

Thank you, anyway!

John » 28 Sep 2010 » Reply

Hi

I want to know how to add custom field for attribute option? For example

if attribute name is “Carat” for diamond product
Its value can be 1, 2, 3, 4, 5

I can Add up to this level in magento, with the help of attribute and its option but I want extra field called “description” which explain what is the meaning of value 1 (carat=1) and what is the mean of 2, admin will write some description about it. So admin will enter data like

English English_Desc French French_Desc
1 This is eng des for 1 1 This is french desc 1

Thanks
John

Mike D » 28 Sep 2010 » Reply

@ John: I am not sure that I follow. Do you want the description to display with the value?

Or is the description only for the admin?

Manuel » 16 Oct 2010 » Reply

Hi, thank for that post it’s so usefull, but still i’ve got some doubts
i’ve got a multi-select attribute added on default set, and i want to retrieve in frontend those attributes who are selected for that product from backend, i’m trying to get that attribute when you click on cart option, so when you click addtocart on View.php and i was trying all day to do it, and i have no lucky.

that my code:

$attributes = $this->getProduct()->getAttributes();
$attributeArray=array();
foreach($attributes as $a){
if($a->getAttributeCode() == 'machine_opt'){
foreach($a->getSource()->getAllOptions() as $option){
$attributeArray[$option['value']] = $option['label'];
}
}
}

Mike D » 17 Oct 2010 » Reply

@Manuel: Try the new code I added:

$attributeId = Mage::getResourceModel('eav/entity_attribute')
->getIdByCode('catalog_product','machine_opt');
$attribute = Mage::getModel('catalog/resource_eav_attribute')->load($attributeId);
$attributeOptions = $attribute ->getSource()->getAllOptions();

web designer in bristol » 19 Oct 2010 » Reply

Hey Mike D,

Just noticed a potentially confusing typo in your first block of code: $attrubuteArray spelt with a ‘u’

(Well, not really a typo because you can call the array whatever you like but you know what I mean)

It’s in the first block of code:

$attribute = Mage::getModel('eav/config')->getAttribute('catalog_product', 'attribute_id');
foreach ( $attribute->getSource()->getAllOptions(true, true) as $option){
$attrubuteArray[$option['value']] = $option['label'];
}

Good article anyhow, found it very useful.

Thanks!

ThreeCheeseHigh » 8 Nov 2010 » Reply

You made my day! Thanks a bunch!

Adrian » 24 Nov 2010 » Reply

Hi Mike, thanks a lot for the article, its very handy and helpful. I was wondering, do you know how can the options for a particular attribute be removed? For instance if I have the attribute color and I want to delete the option ‘red’.

Thanks in advance.

Mike D » 24 Nov 2010 » Reply

Goto manage attributes in the backend and edit the desired attribute. Click on the second tab on the left and that should bring up a page that lists the options for that attribute. Now just delete the option you don’t want.

vignesh » 23 Dec 2010 » Reply

Oh! Thank you very much !

dunhakdis » 17 Jan 2011 » Reply

nice work dude…. ^^<

choussamaster » 22 Jan 2011 » Reply

Some times like in grouped.phtml you have to do it like this
htmlEscape($_item->getAttributeText(‘contenance’)); ?>

igor » 23 Feb 2011 » Reply

How can I make my attribute a link? I am using this to show the actual attribute value, but is there a way to get the URL?

echo $_product->getResource()->getAttribute(‘manufacturer’)->getFrontend()->getValue($_product);

Mike D » 23 Feb 2011 » Reply

I am not exactly sure what you are asking for. The attribute does not have a link. It is just an attribute. Are you asking how to make it a link to a search results page or something?

Mike D » 23 Feb 2011 » Reply

The easiest way would be to just use a switch in your code and just hard code the link you want. Other wise you will need to determine what category it needs to redirect to then use the layered navigation model to create the url based on the category and attribute. And for a beginner that would probably be an under taking. It would also be different based on where on you site you are putting the link.

Chris » 7 Mar 2011 » Reply

I used the first code to pull simple options. I am on Magento 1.5 and it displays ADMIN instead of the Default Store View value. How can I get it to display the Default Store View??

Chris

Chris » 7 Mar 2011 » Reply

Figured it out, just had to turn true to false like so: $attribute->getSource()->getAllOptions(false)

chris » 8 Mar 2011 » Reply

How do you get only attributes that have been assigned to products?

Mike D » 8 Mar 2011 » Reply

Hey Chris,
That is a little trickier. Once I get home I can post some code that I have used to get the attributes, but it is not pretty :(

chris » 9 Mar 2011 » Reply

Were you able to find your code?

Mike D » 10 Mar 2011 » Reply

Hey Chris,
I have updated the post to have an example of pulling attribute values for just values used on products. See the last example. Hope it helps.

chris » 10 Mar 2011 » Reply

Thanks so much!

Dan » 22 Mar 2011 » Reply

Hi,

I have a problem to blank a attribute on the produkt overview. Normally it should work fine with “Used in Product Listing=NO” in attribute manage page.
But for us, it only works for “drop-down-attributes”, nut fpr “text-attributes” for example.
When I choose “Used in Product Listing=NO” für a “text-attribute”, it only blanks out the value of the attribute, not the label.
Do you have an idea for this?

Thank you very much and sorry for my bad english!

getAttributes(); ?>

getIsVisibleOnFront()) : ?>__($attribute->getFrontend()->getValue($_product)) !=”Nein”):?>

__($attribute->getFrontend()->getLabel($_product)) ;?>: __($attribute->getFrontend()->getValue($_product)) ;?>

best regards, Dan

Dan » 22 Mar 2011 » Reply

getAttributes(); ?>

getIsVisibleOnFront()) : ?>__($attribute->getFrontend()->getValue($_product)) !=”Nein”):?>

__($attribute->getFrontend()->getLabel($_product)) ;?>: __($attribute->getFrontend()->getValue($_product)) ;?>

Mike D » 23 Mar 2011 » Reply

Hey Dan,

Try Wrapping you code in the following tags ““, that should allow it to show up properly in the comment box.

Then I should be able to help you better.
Thanks.

Dan » 23 Mar 2011 » Reply

Hi Mike,

Thank you for your advice.

I tried it with the tag, but it didn’t work.

But we found a solution for our problem. The reason why it only blanks out the value of the attribute, not the label in the product overview was:
“Used for Sorting in Product Listing” must be “NO”. Then it works, I don’t know why and I don’t understand the coherence, but it works.

Oleg Kudrenko » 7 Apr 2011 » Reply

Hello from Kiev
Thank you for great post!
This line

//Referenced from /app/code/core/Mage/Eav/Model/Config/php @ line 443
$_product->getResource()->getAttribute('club_type')->getFrontend()->getValue($_product)

can fatal if product not have ‘club_type’ attribute, maybe better

if($attribute = $_product->getResource()->getAttribute('club_type')) {
$attributeValue = $attribute->getFrontend()->getValue($_product);
}

Michael » 17 Jun 2011 » Reply

Your first code snippet worked perfectly. I was trying to get all of the colors used by all products in our Magento storefront. I had looked around here and there for a few days and your example was the first one that worked. Thanks so, so much for posting this.

Chris » 11 Aug 2011 » Reply

Thanks so much for the post. It saved me. Much appreciated!

-Chris

Jerome Dennis D » 31 Aug 2011 » Reply

Thanks a lot Mike.

It helps me a lot to get the attribute labels and values of the drop down type.

enloz » 25 Oct 2011 » Reply

Thanks! This post helped a lot

sunil rana » 1 Nov 2011 » Reply

I found good link on getting product attributes values and labels. It may help you.

http://www.phptechi.com/getting-product-attributes-values-and-labels.html

Canbey Bilgili » 11 Dec 2011 » Reply

Thanks it works. I used it for special_to_date

magento_20 » 12 Dec 2011 » Reply

Hi there,

I am trying to retrieve attributes and all its options for Customers in Magento. This is my code

$attributeIds = Mage::getStoreConfig('customerattributes_options/list/attributes');
$attributes = Mage::getModel('eav/entity_attribute')->getCollection()
->addFieldToFilter('attribute_id', array('in' => $attributeIds));
foreach ($attributes as $attribute)
{
echo 'Code: '. $attribute->getId();
echo 'Index: ' . $attribute->getCode();
echo 'Header: ' . $attribute->getFrontendLabel();
echo 'Type: ' . $attribute->getFrontendInput();
echo ' Options: ' . $attribute->getSource()->getAllOptions(false);

}

But it throws an Error Exception and doesn’t show me any options for Attributes like Gender.
Does anyone know what’s the error in it?

Mike D » 12 Dec 2011 » Reply

@ magento_20,
You need to provide a little more info.
1. What is the error that is thrown?
2. What is the sql that is run?
Get the sql by using the following:

//Put this just above your foreach
print_r($attributes->getSelect()->__toString());die("Sql");

magento_20 » 12 Dec 2011 » Reply

@Mike D

Thanks for your reply. this is the error,
Fatal error: Uncaught exception ‘Mage_Eav_Exception’ with message ‘Source model “” not found for attribute “fax”‘ in /home/wpfsl/public_html/app/Mage.php:549 Stack trace: #0 /home/wpfsl/public_html/app/code/core/Mage/Eav/Model/Entity/Attribute/Abstract.php(387): Mage::exception(‘Mage_Eav’, ‘Source model “”…’) #1 /home/wpfsl/public_html/index.php(91): Mage_Eav_Model_Entity_Attribute_Abstract->getSource() #2 {main} thrown in /home/wpfsl/public_html/app/Mage.php on line 549

And your code doesn’t print out the sql query, I’m afraid.

Mike D » 14 Dec 2011 » Reply

You may need to load each attribute before being able to get the options.

Here is what I would do:
1. Comment out the line where you are getting the options. I think that is what is throwing the error.

2. See if you are actually getting date out of $attribute
A) What class is the $attribute object?

magento_mk » 15 Dec 2011 » Reply

Hi,

I used this code source to load all product attribute names and to fill multisellect component:

$attributeArray=array();
$attributesInfo = Mage::getResourceModel(‘eav/entity_attribute_collection’)
->setEntityTypeFilter(4)
->addSetInfo()
->getData();
foreach ($attributesInfo as $a){
$attributeArray[] = $a[‘frontend_label’];
}
return $attributeArray;

The problem is that I got just the first letters of frontend_label and all of them are big letters. What is wrong in my source code or I have to change something other?
Many thanks in advance!

Mike D » 15 Dec 2011 » Reply

@magento_mk:
1. What is contained in $a?
2. You may need to tell the collection to load other data. Look at the collection model and see what the other options are.

Dave » 3 Jan 2012 » Reply

Fatal error: Uncaught exception ‘Mage_Eav_Exception’ with message ‘Source model “” not found for attribute “fax”‘

This can occur if you have created the attribute but forgot to assign it to the attribute set of the product you are creating.

Aldo Valente » 7 Feb 2012 » Reply

Under Customer -> Customer management -> cart I need to add custom fields to the grid.
I tried adding the fields (’sottotitolo’ and ‘manufacturer’) but they appear without any data.
I modified the file
httpdocs/app/code/core/Mage/Adminhtml/Block/Customer/Edit/Tab/cart.php

These changes work in other sections but in this no.
I do not know how to change the function _prepareCollection ();
In other sections just add
$ collection = Mage :: getResourceModel (‘reports / product_collection’)
-> addOrderedQty ()
-> addAttributeToSelect (array (‘manufacturer’, ‘price’, ‘subtitle’))

the code is this

class Mage_Adminhtml_Block_Customer_Edit_Tab_Cart extends Mage_Adminhtml_Block_Widget_Grid
{

public function __construct($attributes=array())
{
parent::__construct($attributes);
$this->setId(‘customer_cart_grid’.$this->getWebsiteId());
$this->setUseAjax(true);
$this->_parentTemplate = $this->getTemplate();
$this->setTemplate(‘customer/tab/cart.phtml’);
}

protected function _prepareCollection()
{
$customer = Mage::registry(‘current_customer’);
$storeIds = Mage::app()->getWebsite($this->getWebsiteId())->getStoreIds();

$quote = Mage::getModel(‘sales/quote’)
->setSharedStoreIds($storeIds)
->loadByCustomer($customer);

if ($quote) {
$collection = $quote->getItemsCollection(false);
}
else {
$collection = new Varien_Data_Collection();
}

$collection->addFieldToFilter(‘parent_item_id’, array(‘null’ => true));

$this->setCollection($collection);

return parent::_prepareCollection();
}

protected function _prepareColumns()
{

$manufacturer_items = Mage::getModel(‘eav/entity_attribute_option’)->getCollection()->setStoreFilter()->join(‘attribute’,’attribute.attribute_id=main_table.attribute_id’, ‘attribute_code’);
foreach ($manufacturer_items as $manufacturer_item) :
if ($manufacturer_item->getAttributeCode() == ‘manufacturer’)
$manufacturer_options[$manufacturer_item->getOptionId()] = $manufacturer_item->getValue();
endforeach;

$this->addColumn(‘manufacturer’,
array(
‘header’=> Mage::helper(‘catalog’)->__(‘Marchio’),
‘width’ => ’400px’,
‘type’ => ‘options’,
‘index’ => ‘manufacturer’,
‘options’ => $manufacturer_options
));

$this->addColumn(‘sottotitolo’, array(
‘header’ =>Mage::helper(‘reports’)->__(‘Tipologia’),
‘sortable’ => false,
‘index’ =>’sottotitolo’,

));

$this->addColumn(‘product_id’, array(
‘header’ => Mage::helper(‘customer’)->__(‘Product ID’),
‘index’ => ‘product_id’,
‘width’ => ’100px’,
));

$this->addColumn(‘name’, array(
‘header’ => Mage::helper(‘customer’)->__(‘Product Name’),
‘index’ => ‘name’,
));

$this->addColumn(‘sku’, array(
‘header’ => Mage::helper(‘customer’)->__(‘SKU’),
‘index’ => ‘sku’,
‘width’ => ’100px’,
));

$this->addColumn(‘qty’, array(
‘header’ => Mage::helper(‘customer’)->__(‘Qty’),
‘index’ => ‘qty’,
‘type’ => ‘number’,
‘width’ => ’60px’,
));

$this->addColumn(‘price’, array(
‘header’ => Mage::helper(‘customer’)->__(‘Price’),
‘index’ => ‘price’,
‘type’ => ‘currency’,
‘currency_code’ => (string) Mage::getStoreConfig(Mage_Directory_Model_Currency::XML_PATH_CURRENCY_BASE),
));

$this->addColumn(‘total’, array(
‘header’ => Mage::helper(‘customer’)->__(‘Total’),
‘index’ => ‘row_total’,
‘type’ => ‘currency’,
‘currency_code’ => (string) Mage::getStoreConfig(Mage_Directory_Model_Currency::XML_PATH_CURRENCY_BASE),
));

$this->addColumn(‘action’, array(
‘header’ => Mage::helper(‘customer’)->__(‘Action’),
‘index’ => ‘quote_item_id’,
‘type’ => ‘action’,
‘filter’ => false,
‘sortable’ => false,
‘actions’ => array(
array(
‘caption’ => Mage::helper(‘customer’)->__(‘Delete’),
‘url’ => ‘#’,
‘onclick’ => ‘return ‘ . $this->getJsObjectName() . ‘cartControl.removeItem($item_id);’
)
)
));

return parent::_prepareColumns();
}

Ingo » 10 Feb 2012 » Reply

The Exception “Source model ” not found” can also occur if you have upgraded Magento and the select-attribute in eav_attribute is missing its “source_model” value ‘eav/entity_attribute_source_table’. Happened to me when I tried to fetch the values from outside Magento.

Muzammil » 15 May 2012 » Reply

using your last example
How to get Only the Attribute Values that have been used on products

in this code i also also want to fetch their product categories is it possible please help i am new in magento.

Thanks

Dave » 18 Jul 2012 » Reply

Here is the correct list of Entity Type Ids which can be found in the db table “eav_entity_type”. These are the default values that almost everyone’s system will have. However, there is a very small change that you may have different values in eav_entity_type.

Entity Type Ids
1 = customer
2 = customer address
3 = catalog category
4 = catalog product
5 = order
6 = invoice
7 = creditmemo
8 = shipment
9 = rma item (Enterprise only)

Carti Ortodoxe » 27 Jul 2012 » Reply

Hi Mike,

I used your script (first example) in a book selling store, where I needed a page with all available publishings.

Thank you!

builder » 18 Sep 2012 » Reply

if you want to have the translated labels, then you should do as follows: (the example is a custom for price_date attribute)

getPriceDate()) : $price_date = $_product->getResource()->getAttribute('price_date'); $price_date_fe = $price_date->getFrontend(); ?>
__($price_date->getStoreLabel()); ?>: getValue($_product) ?>

builder » 18 Sep 2012 » Reply

lets try again for the last time (this editor is breaking the code)

if ($_product->getPriceDate()) :
$price_date = $_product->getResource()->getAttribute('price_date');
$price_date_fe = $price_date->getFrontend();
$label = this->__($price_date->getStoreLabel());
$value = $price_date_fe->getValue($_product)
endif;

Luke » 4 Nov 2012 » Reply

Thank You

Carlos » 15 Nov 2012 » Reply

Hi, is there a way to disable options of an attribute selectively in the product page based on certain conditions?

rohit goel » 3 Jan 2013 » Reply

Hi can you please tell me how can i show custom product atribute in magento admin sales/order page without showing that atribute on frontend

thanks

Jonathan » 14 Oct 2013 » Reply

Hi there, thanks for the article, i have a question on the last bit of the post

How to get Only the Attribute Values that have been used on products

how do i get this to work with a multi select, im trying to be able to produce a dropdown in php that shows only the attributes selected for the product catalogue i have generated,

Thanks again for the post

Jon

saravanan » 9 Dec 2013 » Reply

hey,can you please help
i need to list out attributes in the category page not for all. only category related attributes. Please help me to resolve it asap. Thanks in advance

Dennis » 9 Apr 2014 » Reply

I am struggeling for about 10 hours now.

What I am trying to accomplish:

The simple php code to display the selected LABELS and VALUES of a multiselect product attribute in list.phtml

I want to use the LABEL as icon image title and the VALUE as the actual image source.

I have search Google and tried many many ways. But nothin is exactly what I need.

Can you please please help me out?

mohsen » 7 Jul 2014 » Reply

Thanks Man!
You saved my time too! :)

WadeO » 7 Jul 2014 » Reply

I was wondering how I could grab a custom attribute lets say “has_lowprice” and pass this along to a grouped product page.

What Im doing on my product pages is grabbing this attribute and displaying information if this product has a certain attribute.

<div id=”lowPrice” data-type=”gethas_lowprice(); ?>”>

The above code will display the “has_lowprice” attribute.

What I need to know is how to pass this on to a grouped product page if any of the products on the page have this has_lowprice attribute.

Thanks for any help on this matter.

Have your say!

Name *

Email *

Message

– See more at: http://www.sharpdotinc.com/magento-getting-product-attributes-values-and-labels/#sthash.ZyleytIX.dpuf

Blog at WordPress.com.

Up ↑