{"id":64,"date":"2015-12-13T12:10:03","date_gmt":"2015-12-13T12:10:03","guid":{"rendered":"http:\/\/magebrew.com\/blog\/?p=64"},"modified":"2015-12-13T12:10:03","modified_gmt":"2015-12-13T12:10:03","slug":"script-to-set-base-image-small-image-and-thumbnail-in-magento","status":"publish","type":"post","link":"https:\/\/magebrew.com\/blog\/script-to-set-base-image-small-image-and-thumbnail-in-magento\/","title":{"rendered":"Script to set Base Image, Small Image and Thumbnail in Magento"},"content":{"rendered":"<p>Sometimes after products import in Magento you may\u00a0face with situation where images were imported successfully but haven&#8217;t been set as Base Image, Small Image or\u00a0Thumbnail. Script below will help you to fix it.<\/p>\n<p><a href=\"http:\/\/magebrew.com\/blog\/wp-content\/uploads\/2015\/12\/magento-set-image.png\"><img loading=\"lazy\" class=\"aligncenter size-medium wp-image-68\" src=\"http:\/\/magebrew.com\/blog\/wp-content\/uploads\/2015\/12\/magento-set-image-300x141.png\" alt=\"magento set image\" width=\"300\" height=\"141\" srcset=\"https:\/\/magebrew.com\/blog\/wp-content\/uploads\/2015\/12\/magento-set-image-300x141.png 300w, https:\/\/magebrew.com\/blog\/wp-content\/uploads\/2015\/12\/magento-set-image-1024x481.png 1024w, https:\/\/magebrew.com\/blog\/wp-content\/uploads\/2015\/12\/magento-set-image.png 1285w\" sizes=\"(max-width: 300px) 100vw, 300px\" \/><\/a><\/p>\n<p><!--more--><\/p>\n<p>So it is going to be a shell script that you can launch from command line. It will help us not to face with\u00a0PHP execution time and memory limits. What is the plan of attack?<\/p>\n<ul>\n<li>Firstly we grab\u00a0all products ids that have &#8216;no_selection&#8217; value in database (<em>catalog_product_entity_varchar<\/em> table) as\u00a0Base Image.<\/li>\n<li>Then get\u00a0products ids that have missing image value record in <em>catalog_product_entity_varchar<\/em> table.<\/li>\n<li>Next step is to combine those ids.<\/li>\n<li>Get\u00a0<em>id to image<\/em> relation from\u00a0<em>catalog_product_entity_media_gallery<\/em> table.<\/li>\n<li>Set Base Image \/\u00a0Small Image \/\u00a0Thumbnail.<\/li>\n<\/ul>\n<p>For the last step we use\u00a0<em>saveAttribute<\/em> method of product resource model. But please note that we have to modify this method to use default store id 0, otherwise you will set images for wrong store.<\/p>\n<p>Here is how this method looks like:<\/p>\n<pre class=\"lang:php decode:true \">\/\/file app\/code\/local\/Magebrew\/SetImage\/Model\/Resource\/Catalog\/Product.php\r\n\r\n    protected function _saveAttributeValue($object, $attribute, $value)\r\n    {\r\n        $write = $this-&gt;_getWriteAdapter();\r\n        \/\/set default store id\r\n        $storeId = Mage_Catalog_Model_Abstract::DEFAULT_STORE_ID;\r\n        $table = $attribute-&gt;getBackend()-&gt;getTable();\r\n\r\n        \/**\r\n         * If we work in single store mode all values should be saved just\r\n         * for default store id\r\n         * In this case we clear all not default values\r\n         *\/\r\n        if (Mage::app()-&gt;isSingleStoreMode()) {\r\n            $storeId = $this-&gt;getDefaultStoreId();\r\n            $write-&gt;delete($table, array(\r\n                'attribute_id = ?' =&gt; $attribute-&gt;getAttributeId(),\r\n                'entity_id = ?' =&gt; $object-&gt;getEntityId(),\r\n                'store_id &lt;&gt; ?' =&gt; $storeId\r\n            ));\r\n        }\r\n\r\n        $data = new Varien_Object(array(\r\n            'entity_type_id' =&gt; $attribute-&gt;getEntityTypeId(),\r\n            'attribute_id' =&gt; $attribute-&gt;getAttributeId(),\r\n            'store_id' =&gt; $storeId,\r\n            'entity_id' =&gt; $object-&gt;getEntityId(),\r\n            'value' =&gt; $this-&gt;_prepareValueForSave($value, $attribute)\r\n        ));\r\n        $bind = $this-&gt;_prepareDataForTable($data, $table);\r\n\r\n        if ($attribute-&gt;isScopeStore()) {\r\n            \/**\r\n             * Update attribute value for store\r\n             *\/\r\n            $this-&gt;_attributeValuesToSave[$table][] = $bind;\r\n        } else if ($attribute-&gt;isScopeWebsite() &amp;&amp; $storeId != $this-&gt;getDefaultStoreId()) {\r\n            \/**\r\n             * Update attribute value for website\r\n             *\/\r\n            $storeIds = Mage::app()-&gt;getStore($storeId)-&gt;getWebsite()-&gt;getStoreIds(true);\r\n            foreach ($storeIds as $storeId) {\r\n                $bind['store_id'] = (int)$storeId;\r\n                $this-&gt;_attributeValuesToSave[$table][] = $bind;\r\n            }\r\n        } else {\r\n            \/**\r\n             * Update global attribute value\r\n             *\/\r\n            $bind['store_id'] = $this-&gt;getDefaultStoreId();\r\n            $this-&gt;_attributeValuesToSave[$table][] = $bind;\r\n        }\r\n\r\n        return $this;\r\n    }\r\n<\/pre>\n<p>And finally our shell script:<\/p>\n<pre class=\"lang:php decode:true \">\/\/file shell\/setBaseImage.php\r\nrequire_once 'abstract.php';\r\n\r\nclass Magebrew_Set_Image extends Mage_Shell_Abstract\r\n{\r\n    \/**\r\n     * Run script\r\n     *\r\n     *\/\r\n    public function run()\r\n    {\r\n        $installer = new Mage_Catalog_Model_Resource_Setup('core_setup');\r\n        try {\r\n            \/\/grab all products ids that have 'no_selection' value in database\r\n            $noSelectionSelect = $installer-&gt;getConnection()-&gt;select()\r\n                -&gt;from(\r\n                    array('product' =&gt; $installer-&gt;getTable('catalog\/product')),\r\n                    array('id' =&gt; 'product.entity_id')\r\n                )\r\n                -&gt;join(\r\n                    array('varchar_table' =&gt; $installer-&gt;getTable('catalog_product_entity_varchar')),\r\n                    'varchar_table.entity_id = product.entity_id',\r\n                    array()\r\n                )\r\n                -&gt;join(\r\n                    array('eav_table' =&gt; $installer-&gt;getTable('eav\/attribute')),\r\n                    'varchar_table.attribute_id = eav_table.attribute_id',\r\n                    array()\r\n                )\r\n                -&gt;where('eav_table.attribute_code = \"image\" AND eav_table.entity_type_id = 4 AND varchar_table.value = \"no_selection\" AND varchar_table.store_id = 0');\r\n\r\n            \/\/get products ids that have missing image value record\r\n            $missingImageValueSelectInner = $installer-&gt;getConnection()-&gt;select()\r\n                -&gt;from(\r\n                    array('product' =&gt; $installer-&gt;getTable('catalog\/product')),\r\n                    array('id' =&gt; 'product.entity_id')\r\n                )\r\n                -&gt;join(\r\n                    array('varchar_table' =&gt; $installer-&gt;getTable('catalog_product_entity_varchar')),\r\n                    'varchar_table.entity_id = product.entity_id',\r\n                    array()\r\n                )\r\n                -&gt;join(\r\n                    array('eav_table' =&gt; $installer-&gt;getTable('eav\/attribute')),\r\n                    'varchar_table.attribute_id = eav_table.attribute_id',\r\n                    array()\r\n                )\r\n                -&gt;where('eav_table.attribute_code = \"image\" AND eav_table.entity_type_id = 4 AND varchar_table.store_id = 0');\r\n\r\n            $missingImageValueSelect = $installer-&gt;getConnection()-&gt;select()\r\n                -&gt;from(\r\n                    array('product' =&gt; $installer-&gt;getTable('catalog\/product')),\r\n                    array('id' =&gt; 'product.entity_id')\r\n                )\r\n                -&gt;where('product.entity_id NOT IN ?', $missingImageValueSelectInner);\r\n\r\n            \/\/combine ids.\r\n            $unitedSselect = $installer-&gt;getConnection()-&gt;select()-&gt;union(array($noSelectionSelect, $missingImageValueSelect));\r\n            $ids = $installer-&gt;getConnection()-&gt;fetchCol($unitedSselect);\r\n            Mage::log(sprintf(\"found %s candidats for setting image\", count($ids)), null, 'image_set.log', true);\r\n\r\n            \/\/Get id to image relation from catalog_product_entity_media_gallery table\r\n            $mediaSelect = $installer-&gt;getConnection()-&gt;select()\r\n                -&gt;from(array('gallery' =&gt; $installer-&gt;getTable('catalog_product_entity_media_gallery')), array('id' =&gt; 'entity_id', 'value'))\r\n                -&gt;join(\r\n                    array('gallery_value' =&gt; $installer-&gt;getTable('catalog_product_entity_media_gallery_value')),\r\n                    'gallery_value.value_id = gallery.value_id AND store_id = 0',\r\n                    array()\r\n                )\r\n                -&gt;where('entity_id in (?)', $ids)\r\n                -&gt;order('position asc');\r\n            $query = $installer-&gt;getConnection()-&gt;query($mediaSelect);\r\n            $idToImage = array();\r\n            while ($row = $query-&gt;fetch()) {\r\n                if (!isset($idToImage[$row['id']])) {\r\n                    $idToImage[$row['id']] = $row['value'];\r\n                }\r\n            }\r\n\r\n            \/\/Mage::log($idToImage, null, 'image_set.log', true);\r\n            \/** @var Magebrew_SetImage_Model_Resource_Catalog_Product $resource *\/\r\n            $resource = Mage::getModel('magebrew_setimage\/resource_catalog_product');\r\n            foreach ($idToImage as $id =&gt; $image) {\r\n                $product = Mage::getModel('catalog\/product')-&gt;setId($id);\r\n                $product-&gt;setStoreId(Mage_Catalog_Model_Abstract::DEFAULT_STORE_ID);\r\n                $product-&gt;setImage($image);\r\n                $product-&gt;setSmallImage($image);\r\n                $product-&gt;setThumbnail($image);\r\n                Mage::log(sprintf(\"trying to set image %s to product %s\", $image, $id), null, 'image_set.log', true);\r\n                $resource-&gt;saveAttribute($product, 'image');\r\n                $resource-&gt;saveAttribute($product, 'small_image');\r\n                $resource-&gt;saveAttribute($product, 'thumbnail');\r\n                echo 'set images for product ' . $id . PHP_EOL;\r\n            }\r\n            echo 'Finished' . PHP_EOL;\r\n        } catch (Exception $e) {\r\n            echo $e-&gt;getMessage() . \"\\n\";\r\n        }\r\n    }\r\n}\r\n\r\n$shell = new Magebrew_Set_Image();\r\n$shell-&gt;run();\r\n<\/pre>\n<p>For complete solution clone this <a href=\"https:\/\/github.com\/magebrew\/magentoSetBaseImage\/\" target=\"_blank\">repo<\/a>, copy files and run script:<\/p>\n<pre class=\"lang:sh decode:true \">php shell\/setBaseImage.php<\/pre>\n<p>Your comments are welcome.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Sometimes after products import in Magento you may\u00a0face with situation where images were imported successfully but haven&#8217;t been set as Base Image, Small Image or\u00a0Thumbnail. Script below will help you to fix it.<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":[],"categories":[2],"tags":[11,12,3,9,10],"_links":{"self":[{"href":"https:\/\/magebrew.com\/blog\/wp-json\/wp\/v2\/posts\/64"}],"collection":[{"href":"https:\/\/magebrew.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/magebrew.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/magebrew.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/magebrew.com\/blog\/wp-json\/wp\/v2\/comments?post=64"}],"version-history":[{"count":5,"href":"https:\/\/magebrew.com\/blog\/wp-json\/wp\/v2\/posts\/64\/revisions"}],"predecessor-version":[{"id":70,"href":"https:\/\/magebrew.com\/blog\/wp-json\/wp\/v2\/posts\/64\/revisions\/70"}],"wp:attachment":[{"href":"https:\/\/magebrew.com\/blog\/wp-json\/wp\/v2\/media?parent=64"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/magebrew.com\/blog\/wp-json\/wp\/v2\/categories?post=64"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/magebrew.com\/blog\/wp-json\/wp\/v2\/tags?post=64"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}