Magento – How do I display only attributes that are assigned to products?

I have the following code, but it displays all attribute options. I want to only display those that have been assigned to a product. What would I change to do this?

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

2 thoughts on “Magento – How do I display only attributes that are assigned to products?”

  1. getAllOptions returns an array whereas we need a collection or query to work with. This first part joins that collection with the relevant attribute table, normally it’s not a good idea to be doing this manually so be careful.

    $entity = 'catalog_product';
    /* @var $options Mage_Eav_Model_Mysql4_Entity_Attribute_Option_Collection */
    
    $options = Mage::getResourceModel('eav/entity_attribute_option_collection')
        ->setAttributeFilter($id)
        ->setStoreFilter(0);
    
    $options->getSelect()->join(
        array('ints'=>"{$entity}_entity_int"),
        '(ints.value=store_value.value_id) AND (ints.attribute_id=main_table.attribute_id)',
        ''
    )->group('option_id');
    

    Now you can just step through the options,

    /* @var $option Mage_Eav_Model_Entity_Attribute_Option */
    foreach ($options as $option) {
        echo $option->getValue();
    }
    

    …or convert to array to get back where you started.

    foreach ($options->toOptionArray() as $option) {
        echo $option['label'];
    }
    

  2. How about this :

    $product = Mage::getModel("catalog/product")->load(167);
        foreach ($product->getOptions() as $o) {
    
            echo "Custom Option TYPE: " . $o->getType() . "<br/>";
            echo "Custom Option TITLE: " . $o->getTitle() . "<br/>";
        } 
    

Leave a Reply

Your email address will not be published. Required fields are marked *