如何以编程方式将基本图像设置为产品的小图像?

时间:2014-11-02 10:48:25

标签: magento magento-1.7

我使用以下代码将基本图像设置为产品的小图像。 在运行代码之前,我有以下信息

---
----
[image] => /s/a/santat.jpg
[small_image] => 
[thumbnail] => /s/a/santa-300.jpg
---

---

<?php
require 'app/Mage.php';
Mage::app();

$products = Mage::getModel('catalog/product')->getCollection()->addAttributeToSelect('*')
                        ->addAttributeToFilter( 'sku', array( 'in' => array( '01Santa') ) );

foreach ($products as $product)
{   
    if (!$product->hasImage()) continue;
        if (!$product->hasSmallImage())
        {   

            try{
                $product->setSmallImage($product->getImage());
            }
            catch(Exception $e) 
            {               
                echo $e->getMessage();
            }
        }
        $product->save();       
}
?>

代码运行后,如果我打印

,我会关注
print_r($product);

[image] => /s/a/santa.jpg
[small_image] => /s/a/santa.jpg
[thumbnail] => /s/a/santa-300.jpg

但仍然在管理员中没有图像被设置为小图像为什么?(我正在使用多网站设置)

enter image description here

2 个答案:

答案 0 :(得分:0)

您需要更改代码

    $product = Mage::getModel('catalog/product')->load($id);
$mediaGallery = $product->getMediaGallery();
if (isset($mediaGallery['images'])){
    foreach ($mediaGallery['images'] as $image){
        Mage::getSingleton('catalog/product_action')->updateAttributes(array($product->getId()), array('small_image'=>$image['file']), 0);
        break;
    }
}

答案 1 :(得分:0)

 <?php
    require 'app/Mage.php';
    Mage::app();

    $products = Mage::getModel('catalog/product')->getCollection()
                            ->addAttributeToFilter( 'sku', array( 'in' => array("004XmasVacGrnShtrs") ) );                      

    foreach($products as $product)
    {
        $productId = $product->getId();
        echo "<br>";    
                //load the product
        $product = Mage::getModel('catalog/product')->setStoreId("14")->load($productId);
            //get all images
        $image = $product->getImage(); //Get product base image
        Mage::getSingleton('catalog/product_action')->updateAttributes(array($product->getId()), array('small_image'=>$image), 14); //14 is store id    
    }
    echo "done";

    ?>