let me first explain my problem, I need to change my atribute for free shipping for all the products in a single category. I know how to read atribute value, because I am displaying banner when a product has a free shipping atribute.
Now, what if I have to set these atribute values for all products in a single category?
What will be the best way to achieve that?
It would be very usefull if, I could change values from backend.
I have found, that you can add an atribute for a category, but sometimes, those atributes won't be the same.
I am using Magento 1.9.2
Thank you!
It's not possible to make filter products by category n admin panel. Simple script will make this
<?php
require 'app/Mage.php';
$products = Mage::getModel('catalog/category')->load($category_id)
->getProductCollection()
->addAttributeToSelect('*') // add all attributes - optional
->addAttributeToFilter('status', 1) // enabled
->addAttributeToFilter('visibility', 4); //visibility in catalog,search
foreach($products as $product) {
$product->setAttribute('new value');
$product->save();
}
Just create new php file, put it in main Magento diroctory and run by cli or url.
I am trying to load a custom category in the catalog/category/view.phtml to archive this I use:
<?php
$_category = Mage::getModel('catalog/category')->load(47);
$_productCollection = $_category->getProductCollection();
if($_productCollection->count()) {
foreach( $_productCollection as $_product ):
echo $_product->getProductUrl();
echo $this->getPriceHtml($_product, true);
echo $this->htmlEscape($_product->getName());
endforeach;
}
?>
I can load the URL for example, now I want to load a custom attribute for example color:
$_product->getResource()->getAttribute('color')->getFrontend()->getValue($_product)
This code does not work, I am 100% sure the color attribute is set to show in the category listing and also that the items in this category have this fields fill. I know this because this code works on list.html.
What I am doing wrong? I am working with 1.7.0.2.
The expected result is to show all COLOR attibutes from a custom cateogory in
catalog/category/view.phtml
I can't believe I just found the answer. Because we are not in a regular category listing we need to add the custom attributes to the collection.
Here is the code:
$_productCollection = $_category->getProductCollection()
->addAttributeToSelect('color');
If "color" is in the flat table you should be able to
$_product->getColor();
If this attribute is not in the collection, you can either add it to the flat table by making the attribute filterable, add it in the PHP collection call
$_productCollection = $_category->getProductCollection()
->addAttributeToSelect('color');
Or load the product model to get all of the attributes
$_product = Mage::getModel('catalog/product')->load($_product->getId());
echo $_product->getColor();
Make this attribute visible in listing/frontend
Run Reindexing
foreach( $_productCollection as $_product ):
echo $_product->getProductUrl();
in this code var_dump $_product->getData(); check if this var_dump results in that specific attribute value getting displayed.
Note:
$_product->getResource()->getAttribute('color')->getFrontend()->getValue($_product)
is not a very efficient way of calling.
I am trying to display a grouped product's price on the product view page in Magento 1.7.0.2, just as it is being displayed in the category product listing ("Starting at: xx.xx"). I thought I could just use
$this->getPriceHtml($_product, true);
to do so because it works the same way in the category product listing, but as everything I tried to do in Magento, it is not that easy because that method doesnt return anything on the product view page.
I looked a little deeper into Magento's code and figured out that the cause of this problem is the product's minimal price data not being set on the product view page ($_product->getMinimalPrice() returns null).
Therefore I did some research on how to load a product's minimal price which brought up ideas like
$_product->getPriceModel()->getMinimalPrice($_product);
which doesnt work because apparently that method was deprecated and removed in one of the last updates or
$priceModel = Mage::getResourceModel('catalogindex/price');
$priceModel->setStoreId(Mage::app()->getStore()->getId());
$priceModel->setCustomerGroupId(Mage::getSingleton('customer/session')->getCustomerGroupId());
$minimalPrices = $priceModel->getMinimalPrices(array($_product->getId()));
$minimalPrice = $minimalPrices[0];
$_product->setData('minimal_price', $minimalPrice['value']);
$_product->setData('minimal_tax_class_id', $minimalPrice['tax_class_id']);
which doesnt work either because the table 'catalogindex_minimal_price' is empty.
So my question is, how does Magento load the minimal price in the category product listing?
I looked a little deeper into Magento's code and tracked down how Magento loads the products of the product list.
When viewing the product list, the product collection is loaded by the model Mage_Catalog_Model_Layer, which adds the minimal price and other stuff to the products in the collection by adding joins to the collection’s SQL, but I have not yet found a model that does the same thing for single products instead of collections.
Because I don’t want to use a direct SQL query, I checked out the CatalogIndex module, but that module seems not to be working at all because all its indexing tables are empty or even corrupted.
$data_grouped = Mage::getModel("catalogindex/data_grouped");
$minimal = $data_grouped->getMinimalPrice(array($_product->getId()), Mage::app()->getStore());
looked good at first but it gives me the following error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'catalog_product_index_price.value' in 'field list'
The CatalogIndex module is either deprecated or I’m just too stupid to enable it.
However, I have now created a workaround in my price.phtml template, which uses the same method to retrieve the minimal price and tax percents as the product list does:
At the beginning of the template I added the following:
$this->setProduct(
Mage::getModel("catalog/product")->getCollection()
->addAttributeToSelect(Mage::getSingleton("catalog/config")->getProductAttributes())
->addAttributeToFilter("entity_id", $this->getProduct()->getId())
->setPage(1, 1)
->addMinimalPrice()
->addFinalPrice()
->addTaxPercents()
->load()
->getFirstItem()
);
which may not be the perfect solution, but it does the job and it does it a little cleaner than iterating over all child products and finding the minimal price that way.
This isn't an answer as much as a big HTML comment on Subsurf's answer. If you're reading this, you might be implementing your own custom module to display a product list. In my case, it's a single page just for wholesalers. My goal was to get a list of my own company's products and give them a list like it was another category. I copied my template's list.phtml to my new content.phtml. But getMinimalPrice() was returning NULL, meaning that when this code calls the getPriceHtml(), price.phtml wasn't showing wholesale pricing.
I did a simple module with index controller and a content.phtml. Using the boilerplate I see all over the net, in the indexController.php file, change:
$block = $this->getLayout()->createBlock(
'Mage_Core_Block_Template',
'b2b',
array('template' => 'b2b/content.phtml')
);
to:
$block = $this->getLayout()->createBlock(
'Mage_Catalog_Block_Product_List',
'b2b',
array('template' => 'b2b/content.phtml')
);
This does a lot of the heavy lifting for you to show the products list correctly.
Now, on to the template file, in my case content.phtml, you get your product collection and then use Subsurf's code in the top of the foreach() which repeats.
$_productCollection = Mage::getModel('catalog/product')
->getCollection()
// ->addAttributeToSelect('*')
// doesn't work ->addAttributeToSelect('special_price')
->addAttributeToSelect('sku')
->addAttributeToFilter('status', 1)
->addAttributeToFilter('visibility', 4)
// http://stackoverflow.com/questions/1332742/magento-retrieve-products-with-a-specific-attribute-value
->addFieldToFilter( array(
array('attribute'=>'manufacturer','eq'=>'143')
, array('attribute'=>'manufacturer','eq'=>'139')
))
;
echo "<p>There are ".count($_productCollection)." products: </p>";
echo '<div class="category-products">';
// List mode
if($this->getMode()!='grid') {
$_iterator = 0;
echo'<ol class="products-list" id="products-list">';
foreach ($_productCollection as $_product) {
?> <li class="item<?php if( ++$_iterator == sizeof($_productCollection) ): ?> last<?php endif; ?>">
<?php
$_product=Mage::getModel("catalog/product")->getCollection()
->addAttributeToSelect(Mage::getSingleton("catalog/config")->getProductAttributes())
->addAttributeToFilter("entity_id", $_product->getId())
->setPage(1, 1)
->addMinimalPrice()
->addFinalPrice()
->addTaxPercents()
->load()
->getFirstItem()
);
echo "Minimal price: ".$_product->getMinimalPrice()."<br>\n";
Since this isn't a single product's page and I'm using other template code, $this->setProduct() didn't do anything for me. I guessed if there was a set, there might be a get, so $_product=$this->getProduct() was the magic my template's price.phtml needed to work properly. Then I noticed I could just assign the Mage:: in setProduct() directly to $_product.
Thanks, Subsurf!!!
There is another way that will still allow you to use $this->getPriceHtml($_product, true); in your template, which then handles all the complex price display rules and puts "Starting at" before grouped product prices.
I'm using this for a custom featured product block. In a block class I have this function:
class MyCompany_Catalog_Block_Product_Featured extends Mage_Catalog_Block_Product_Abstract {
public function setGroupedProductPrice($group_product) {
$prices = array();
foreach ($group_product->getTypeInstance()->getChildrenIds($group_product->getId()) as $ids) {
foreach ($ids as $id) {
$product = Mage::getModel('catalog/product')->load($id);
$prices[] = $product->getPriceModel()->getPrice($product);
}
}
ksort($prices);
$group_product->setPrice(array_pop($prices));
}
}
Then in the template:
<?php
if ($_product->getTypeId() == 'grouped')
$this->prepareGroupedProduct($_product);
echo $this->getPriceHtml($_product, true);
?>
The following does the trick without using a product collection:
$priceResource = Mage::getResourceSingleton('catalogindex/price');
$select = $priceResource->getReadConnection()->select();
$select->from(
array('price_table' => $priceResource->getMainTable())
)
->where('price_table.entity_id = ?', $_product->getId())
->where('price_table.website_id = ?', Mage::app()->getStore()->getWebsiteId())
->where('price_table.customer_group_id = ?', Mage::getSingleton('customer/session')->getCustomerGroupId());
$result = $priceResource->getReadConnection()->fetchRow($select);
This code is adapted from \Mage_CatalogIndex_Model_Resource_Price::getMinimalPrices and made suitable for one single product.
I'm looking to display a featured products collection, based on a featured attribute filter. I get this basically working okay. The part I'm struggling with is that the URL that gets attached to 'getProductUrl()' is wrong.
Comparing the system urls without rewriting them, I noticed that I get this type of url:
catalog/product/view/id/1148/category/6
The category ID at the end is wrong. It shows the parent category ID. If I could get the correct subcategory ID in which those products are assigned, at the end of this URL, then my rewrite would probably work.
Here's my current code, in a featured.phtml template:
<?php
// get all products that are marked as featured
$collection = Mage::getModel('catalog/product')->getCollection();
$collection->addAttributeToSelect('*');
$collection->addAttributeToFilter('featured', array('Yes' => true));
$collection->setOrder('entity_id', 'desc');
$collection->addUrlRewrite($categoryId);
?>
and
<?php foreach ($collection as $_product) : ?>
Can anybody help? Thanks in advance.
Additional notes: the products are in a subcategory but this collection is pulled on the landing page of its parent category and on the home CMS page.
I get: www.sitename.com/product_url_key.html
I want: www.sitename.com/category_path/product_url_key.html
I installed Magento v1.3.2.3 and added most of my product inventory. However, I can only get 5 items to display on the homepage. I need all my products to show up there. How?
This is currently the code I am using.
{{block type="catalog/product_new" name="home.catalog.product.new" alias="product_homepage" template="catalog/product/new.phtml"}}
I found this on the magento community forum.
This link explains how to display products in a particular category on the homepage. You just have to remove the category filter from the code given there to get all the products.
$products = $product->setStoreId($storeId)
->getCollection()
->addAttributeToFilter(‘visibility’, $visibility)
->addCategoryFilter($category)
->addAttributeToSelect(array(‘name’), ‘inner’) //you need to select “name” or you won’t be able to call getName() on the product
->setOrder(‘name’, ‘asc’)
;
change this to
$products = $product->setStoreId($storeId)
->getCollection()
->addAttributeToFilter(‘visibility’, $visibility)
->addAttributeToSelect(array(‘name’), ‘inner’)
->setOrder(‘name’, ‘asc’)
;
That should set you on the right track. Good luck!