我有一家商店,提供可配置且简单的产品(多种颜色)。目前,我们选择一个简单的产品图像并将其分配给可配置的产品,这就是列表页面上显示的内容。问题是,如果该特定颜色缺货,我们就会陷入代表缺货产品的图像(并且必须手动更新该图像)。
有没有办法在列表页面上使用简单的产品图像,同时仍然允许控制使用哪个图像?我知道如何使用列表页面上的简单图像,但我不知道如何指定哪个简单图像(目前我只是抓取简单产品并从列表中的第一个产品中提取图像)。
如果我能找到一种方法来对可配置产品中的简单产品进行排序(即,确保对于产品 A,简单产品被排序为黑色、绿色、蓝色,对于产品 B,简单产品被排序为绿色、蓝色、黑色),我想我可以弄清楚剩下的事情。
有什么想法吗?
想通了。我为简单产品添加了一个名为“sort_order”的新属性。然后,我覆盖了目录/产品助手并添加了以下方法:
public function getSortedSimpleProducts($product) {
$products = array();
$allProducts = $product->getTypeInstance(true)->getUsedProducts(null, $product);
foreach ($allProducts as $product) {
if ($product->isSaleable()) {
$products[] = $product;
}
}
$sorted_products = array();
$unsorted_products = array();
foreach ($products as $simple_product) {
$sort_order = $simple_product->getData('sort_order');
if ($sort_order) {
$sorted_products[$sort_order] = $simple_product;
}
else {
$unsorted_products[] = $simple_product;
}
}
$final_products = $sorted_products;
if (count($unsorted_products) > 0) {
$final_products = array_merge($sorted_products, $unsorted_products);
}
if (count($final_products) > 0) {
sort($final_products);
}
return $final_products;
}
然后,在 list.phtml 模板中,围绕这一行:
<?php $i=0; foreach ($_productCollection as $_product): ?>
我添加了以下代码:
$image_product = $_product;
$products = $this->helper('catalog/product')->getSortedSimpleProducts($_product);
if (count($products) > 0) {
$image_product = $products[0];
}
并更新了我的图像标签:
<img src="<?php echo $this->helper('catalog/image')->init($image_product, 'small_image')->resize(189,238); ?>" alt="<?php echo $this->stripTags($this->getImageLabel($_product, 'small_image'), null, true) ?>" />
然后我重写了 Mage_Catalog_Block_Product_View_Type_Configurable 以使 getAllowProducts 按新的排序顺序(决定视图页面上颜色的排序)排序:
public function getAllowProducts() {
if (!$this->hasAllowProducts()) {
$products = array();
$allProducts = Mage::helper('catalog/product')->getSortedSimpleProducts($this->getProduct());
foreach ($allProducts as $product) {
if ($product->isSaleable()) {
$products[] = $product;
}
}
$this->setAllowProducts($products);
}
return $this->getData('allow_products');
}
然后更新media.phtml文件:
$childProducts = $this->helper('catalog/product')->getSortedSimpleProducts($_product);
这样产品图片也将使用相同的排序。
我希望这不会对性能产生巨大影响(客户表示这是一个主要要求)。如果客户没有在简单产品上设置排序顺序,它会很好地降级。而且,如果库存缺货,它将显示排序顺序中下一个的图像。
欢迎大家批评指正!