2

I am trying to get custom attribute value in frontend

I am trying below code in view.phtml , its working fine.

when i used the same code in other .phtml file its giving error :

Fatal error: Call to a member function getId() on a non-object in

<?php 

$product_id = Mage::registry('current_product')->getId();
$_product=Mage::getModel('catalog/product')->load($product_id);
$attribute = $_product->getResource()->getAttribute('cod_available');
if ($attribute)
{
    echo $attribute_value = $attribute ->getFrontend()->getValue($_product);
}
?>
Baby in Magento
  • 3,167
  • 16
  • 83
  • 221

4 Answers4

3

Replace your code from:

<?php 

$product_id = Mage::registry('current_product')->getId();
$_product=Mage::getModel('catalog/product')->load($product_id);
$attribute = $_product->getResource()->getAttribute('cod_available');
if ($attribute)
{
    echo $attribute_value = $attribute ->getFrontend()->getValue($_product);
}
?>

To:

view.phtml

<?php 
$currentProduct = Mage::registry('current_product');
if($currentProduct) {
    $attribute = $currentProduct->getResource()->getAttribute('cod_available');
    if ($attribute) {
        echo $attribute_value = $attribute ->getFrontend()->getValue($_product);
    }
}
?>

other .phtml (But must be available getproduct() function in block file)

<?php 

$product = $this->getProduct();
if($product->getId()) {
    $attribute = $product->getResource()->getAttribute('cod_available');
    if ($attribute) {
        echo $attribute_value = $attribute ->getFrontend()->getValue($_product);
    }
}
?>
Abdul
  • 9,701
  • 1
  • 20
  • 43
1

use this

 $product_id = $this->getProduct()->getId();
     $_product=Mage::getModel('catalog/product')->load($product_id);
$attribute = $_product->getResource()->getAttribute('cod_available');
if($_product->getData('cod_available')) { echo 'available'; }
?>
Qaisar Satti
  • 32,469
  • 18
  • 85
  • 137
1

If you using this code for product details page, please try:

$product_id = $this->getRequest()->getParam('id'); $_product=Mage::getModel('catalog/product')->load($product_id);

Harry Nguyen
  • 2,815
  • 17
  • 13
1

when i used the same code in other .phtml file its giving error :

Fatal error: Call to a member function getId() on a non-object in

Mage::registry('current_product') 

Give Product object only on product page.your have used same code in other non-product page that's why it gives error.

Minesh Patel
  • 2,193
  • 12
  • 23