Home

Showing posts with label Magento. Show all posts
Showing posts with label Magento. Show all posts

Wednesday, February 7, 2018

How to get All Sub Category in Magento using Parent Category Id ?

<?php
require_once 'app/Mage.php';
set_time_limit(0);
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('memory_limit', '1024M');
ini_set('max_execution_time', 12000);
Mage::app();
Mage::app()->getStore()->setId(Mage_Core_Model_App::ADMIN_STORE_ID);


?>
<?php $_helper = Mage::helper('catalog/category') ?>
<?php $categoryId = 12449;?>
<?php $category = Mage::getModel('catalog/category')->load($categoryId) ?>
<?php $_categories = $category->getChildrenCategories() ?>

<?php if (count($_categories) > 0): ?>
    <ul>
        <?php foreach($_categories as $_category): ?>
            <li>
                <a href="<?php echo $_helper->getCategoryUrl($_category) ?>"><?php echo $_category->getName() ?></a>
                <?php $_category = Mage::getModel('catalog/category')->load($_category->getId()) ?>
                <?php if($_category->hasChildren()):?>
                <?php $_subcategories = $_category->getChildrenCategories() ?>
                    <ul>
                        <?php foreach($_subcategories as $_subcategory): ?>
                            <li>
                                <a href="<?php echo $_helper->getCategoryUrl($_subcategory) ?>"><?php echo $_subcategory->getName() ?></a>
                                <?php $_category2 = Mage::getModel('catalog/category')->load($_subcategory->getId()) ?>
                                <?php if($_category2->hasChildren()):?>
                                <?php $_subcategories2 = $_category2->getChildrenCategories() ?>
                                    <ul>
                                        <?php foreach($_subcategories2 as $_subcategory2): ?>
                                            <li>
                                                <a href="<?php echo $_helper->getCategoryUrl($_subcategory2) ?>"><?php echo $_subcategory2->getName() ?></a>
                                            </li>
                                        <?php endforeach; ?>
                                    </ul>
                                <?php endif; ?>

                            </li>
                        <?php endforeach; ?>
                    </ul>
                <?php endif; ?>
            </li>
        <?php endforeach; ?>
    </ul>
<?php endif; ?>


Second Method 

$category_ids = array();
$catID = 12449;

function retrieveAllChilds($id = null, $childs = null) {
    $category = Mage::getModel('catalog/category')->load($id);
    $subCategory = $category->getResource()->getChildren($category, true);

foreach ($subCategory as $categoryID)
{
$sCategory = Mage::getModel('catalog/category')->load($categoryID);
//$catnames = array();
//$category_ids = array();
foreach ($sCategory->getParentCategories() as $parent) {
//$catnames[] = $parent->getName();
//array_push($category_ids,$parent->getName());
$category_ids[$parent->getId()] = $parent->getName();
}
//echo  implode('->',$catnames);
//echo '<br>';
/*echo "<pre>";
print_r($category_ids);*/

}
return $category_ids;
}

$dd = retrieveAllChilds(12449);

echo "<pre>";
print_r($dd);



Monday, November 20, 2017

How to create category in magento with tree ?

<?php
require_once '../app/Mage.php';
set_time_limit(0);
ini_set('memory_limit','1024M');
Mage::app();
Mage::app()->getStore()->setId(Mage_Core_Model_App::ADMIN_STORE_ID);

$array = array("Cat-A > Cat-B > Cat-C > Cat-G","Cat-D > Cat-E > Cat-F");

for($i=0;$i<count($array);$i++)
{
    $explode = explode(">",$array[$i]); 
    $trimmed_array=array_map('trim',$explode);   
   
    $previous_cat_id = 0;
    for($d=0;$d<count($trimmed_array);$d++)
    {       
       $cat_name = $trimmed_array[$d];   
     
       $_category = Mage::getResourceModel('catalog/category_collection')
        ->addFieldToFilter('name', $cat_name)
        ->getFirstItem();

       $categoryId = $_category->getId();     

       if($categoryId == '')
       {
           if($previous_cat_id == 0)
           {
                $parentId = '2';
           }else
           {
               $parentId = $previous_cat_id;
           }         
            try{
               $category = Mage::getModel('catalog/category');
               $category->setName($cat_name);         
               $category->setIsActive(1);
               $category->setDisplayMode('PRODUCTS');
               $category->setIsAnchor(1); //for active anchor
               $category->setStoreId(Mage::app()->getStore()->getId());
               $parentCategory = Mage::getModel('catalog/category')->load($parentId);
               $category->setPath($parentCategory->getPath());
               $category->save();
               $previous_cat_id = $category->getId();
           } catch(Exception $e) {
               print_r($e);
           } 
       }else
       {         
           if($previous_cat_id !="" && $categoryId!="")
           { 
                $categoryId = $categoryId;
                $parentId = $previous_cat_id;

                $category = Mage::getModel('catalog/category')->load($categoryId);
                $category->move($parentId, null);
                $previous_cat_id = 0;
           }else
           {
                $previous_cat_id = $categoryId;
           }         
       }
    } 
}
?>

Tuesday, September 26, 2017

How to remove all product image in magento ?

<?php
require_once '../app/Mage.php';
set_time_limit(0);
ini_set('memory_limit','1024M');
umask(0);
Mage::app('admin');
Mage::setIsDeveloperMode(true);

$productCollection=Mage::getResourceModel('catalog/product_collection');
foreach($productCollection as $product)
{
    echo $product->getId();
    echo "<br/>";
    $MediaDir=Mage::getConfig()->getOptions()->getMediaDir();
    echo $MediaCatalogDir=$MediaDir .DS . 'catalog' . DS . 'product';
    echo "<br/>";

    $MediaGallery=Mage::getModel('catalog/product_attribute_media_api')->items($product->getId());
    echo "<pre>";
    print_r($MediaGallery);
    echo "</pre>";

    foreach($MediaGallery as $eachImge){
        $MediaDir=Mage::getConfig()->getOptions()->getMediaDir();
        $MediaCatalogDir=$MediaDir .DS . 'catalog' . DS . 'product';
        $DirImagePath=str_replace("/",DS,$eachImge['file']);
        $DirImagePath=$DirImagePath;
        // remove file from Dir
        $io     = new Varien_Io_File();
        $io->rm($MediaCatalogDir.$DirImagePath);

        $remove=Mage::getModel('catalog/product_attribute_media_api')->remove($product->getId(),$eachImge['file']);
    }
}
?>

Saturday, July 22, 2017

Base url without index.php in magento

<?php
            echo Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB);
?>

Thursday, June 22, 2017

How to add images for products in magento pragmatically ?

Use can upload Base-Image, Small-Image, Thumbnail-Image, and Image-Gallery for the product using CSV file in Magento programmatically.
=====================================================================
<?php
require_once '../app/Mage.php';
set_time_limit(0);
ini_set('memory_limit','1024M');
Mage::app();
Mage::app()->getStore()->setId(Mage_Core_Model_App::ADMIN_STORE_ID);

// Images with SKU
$importDir = Mage::getBaseDir('media') . DS . 'import/diamond/shape/big/';
$file_handle = fopen("images5.csv", "r");
$c = 0;


while (!feof($file_handle) ) {
$line_of_text = fgetcsv($file_handle, 10000);

if($line_of_text[0] !="")
{
$productSKU = $line_of_text[0];
$ourProduct = Mage::getModel('catalog/product')->loadByAttribute('sku',$productSKU);
$lastproductSKU = $productSKU;

$basefileName = $line_of_text[1];
$smallfileName = $line_of_text[2];
$thumbfileName = $line_of_text[3];

$basefilePath = $importDir.$basefileName;
$smallfilePath = $importDir.$smallfileName;
$thumbfilePath = $importDir.$thumbfileName;

// Base Image
if (file_exists($basefilePath)) {
$ourProduct->addImageToMediaGallery($basefilePath, array('image'), false, false);
}

// Small Image
if (file_exists($smallfilePath)) {
$ourProduct->addImageToMediaGallery($smallfilePath, array('small_image'), false, false);
}

// thumbnail Image
if (file_exists($thumbfilePath)) {
$ourProduct->addImageToMediaGallery($thumbfilePath, array('thumbnail'), false, false);
}

$extrafileName = $line_of_text[4];
$extrafilePath = $importDir.$extrafileName;
if (file_exists($extrafilePath)) {
$ourProduct->addImageToMediaGallery($extrafilePath, null, false, false);
}
$ourProduct->save();
}else
{
$ourProduct = Mage::getModel('catalog/product')->loadByAttribute('sku',$lastproductSKU);
$extrafileName = $line_of_text[4];
$extrafilePath = $importDir.$extrafileName;
if (file_exists($extrafilePath)) {
$ourProduct->addImageToMediaGallery($extrafilePath, null, false, false);
$ourProduct->save();
}
}
$c++;
}
fclose($file_handle);
?>

Please check image for CSV format.


How to get all images of particular product in magento pragmatically ?

<?php
require_once '../app/Mage.php';
set_time_limit(1);
ini_set('memory_limit','1024M');
ini_set('max_execution_time', 3000);
Mage::app();
Mage::app()->getStore()->setId(Mage_Core_Model_App::ADMIN_STORE_ID);

// Get Product SKU using csv file
$file_handle = fopen("skus.csv", "r");
$c = 1;
while (!feof($file_handle) ) {
$line_of_text = fgetcsv($file_handle, 10000);
$productSKU = $line_of_text[0];


if($line_of_text[0]!="")
{
$sku = substr($productSKU,0,-1);
$id = Mage::getModel('catalog/product')->getIdBySku($sku);
if (false !== $id) {
  //sku exists
$model =  Mage::getModel('catalog/product')->loadByAttribute('sku',$sku);
$productMediaConfig = Mage::getModel('catalog/product_media_config');

if($model->getImageUrl())
{
$baseImageUrl  = $productMediaConfig->getMediaUrl($model->getImage());
$smallImageUrl = $productMediaConfig->getMediaUrl($model->getSmallImage());
$thumbnailUrl  = $productMediaConfig->getMediaUrl($model->getThumbnail());

$basefileName = explode("/",$model->getImage());
$smallfileName = explode("/",$model->getSmallImage());
$thumbfileName = explode("/",$model->getThumbnail());

echo $c.")baseImageUrl ".$sku."==>".$baseImageUrl;
echo "<br>";
echo $c.")smallImageUrl ".$sku."==>".$smallImageUrl;
echo "<br>";
echo $c.")thumbnailUrl ".$sku."==>".$thumbnailUrl;


$gallery_images = Mage::getModel('catalog/product')->load($model->getId())->getMediaGalleryImages();

$items = array();

foreach($gallery_images as $g_image) {
$items[] = $g_image['url'];
}

echo "<pre>";
print_r($items);
echo "</pre>";
echo "<br>";
echo "<br>";echo "<br>";*/
}
echo "<br>";
$c++;
}
else {
  //sku does not exist
  echo $productSKU."==>sku does not exist";
  echo "<br>";
}
}
}
fclose($file_handle);
?>

Please check image for CSV format.


Monday, January 23, 2017

How to programmatically update short and long description using csv file for magento products ?

<?php
require_once '../app/Mage.php';
umask(0) ;
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);

$csv = new Varien_File_Csv();
$data = $csv->getData('sku_description.csv'); //path to csv
array_shift($data);

for($i=0;$i<count($data);$i++)
{
if($data[$i][0] != "")
{
$product_sku = $data[$i][0];
$short_description = $data[$i][1];
$long_description = $data[$i][2];

$product = Mage::getModel('catalog/product')->loadByAttribute('sku',$product_sku);

if($product) {
$product->setShortDescription($short_description);
$product->setDescription($long_description);
$product->save();
echo "Updated product " . $productSku . "<br>";
}else
{
echo "Not - Updated product " . $productSku . "<br>";
}
}
}
?>

Please check image for CSV format.


Monday, January 2, 2017

How to change a product dropdown attribute to a multiselect in Magento using Database Query ?

UPDATE eav_attribute SET
entity_type_id = '10', // set here entity_type_id  from eav_attribute
attribute_model = NULL,
backend_model = 'eav/entity_attribute_backend_array',
backend_type = 'varchar',
backend_table = NULL,
frontend_model = NULL,
frontend_input = 'multiselect',
frontend_class = NULL
WHERE attribute_id = '1100'; // set here attribute_id  from eav_attribute


INSERT INTO catalog_product_entity_varchar ( entity_type_id, attribute_id, store_id, entity_id, value)
SELECT entity_type_id, attribute_id, store_id, entity_id, value
FROM catalog_product_entity_int
WHERE attribute_id = 1100; // set here attribute_id  from eav_attribute


DELETE FROM catalog_product_entity_int
WHERE entity_type_id = 10 and attribute_id = 1100; // set here attribute_id  from eav_attribute

How to add to cart configurable product in magento programmatically ?

<?php

include 'app/Mage.php';

Mage::app();

// Need for start the session

Mage::getSingleton('core/session', array('name' => 'frontend'));

try {

    $product_id = '389';

    $product = Mage::getModel('catalog/product')->load($product_id);

    $cart = Mage::getModel('checkout/cart');

    $cart->init();

    $params = array(

        'product' => $product_id,

        'super_attribute' => array(

            1102 => 351,              
        ),

        'qty' => 1,

    );

    $cart->addProduct($product, $params);

    $cart->save();

    Mage::getSingleton('checkout/session')->setCartWasUpdated(true);

    Mage::getSingleton('core/session')->addSuccess('Product added successfully');

    header('Location: ' . 'index.php/checkout/cart/');

} catch (Exception $e) {

    echo $e->getMessage();

}

?>

Saturday, December 24, 2016

How to set character limit for Product Name, Description, Short Description in Magento ?

<?php
$productName = $_helper->productAttribute($_product, $_product->getName(), 'name');
echo Mage::helper('core/string')->truncate($productName, $length = 50, $etc = '...', $remainder = '', $breakWords = true);
?>

Wednesday, September 28, 2016

How to get all configurable products in magento ?

$collection = Mage::getResourceModel('catalog/product_collection')
            ->addAttributeToSelect('*')
            ->addAttributeToFilter('type_id','configurable');

foreach ($collection as $product)
{
     echo $product->getName();
}

Saturday, August 20, 2016

How to Change the price before adding to cart in magento with custom option selection price?

Put below code in app\code\community\YBizz\PriceChange\Model\Observer.php
<?php
class DRC_PriceChange_Model_Observer  {

    public function change_price(Varient_Event_Observer $observer) 
    {   
        $item = $observer->getQuoteItem();
        if ($item->getParentItem()) {$item = $item->getParentItem();}
        $price = $item->getProduct()->getFinalPrice();
        $new_price = 20 + $price;

        $item->setCustomPrice($new_price);
        $item->setOriginalCustomPrice($new_price);
        $item->getProduct()->setIsSuperMode(true);      
    }
}
?>

Wednesday, August 3, 2016

How to get value of Attribute Option in magento ?

<?php
require_once '../app/Mage.php';
umask(0) ;
Mage::app();

function getAttributeOptionValue($arg_attribute, $arg_value)
{
$attribute_model = Mage::getModel('eav/entity_attribute');
$attribute_options_model= Mage::getModel('eav/entity_attribute_source_table');  
$attribute_code = $attribute_model->getIdByCode('catalog_product', $arg_attribute);
$attribute = $attribute_model->load($attribute_code);
$attribute_table = $attribute_options_model->setAttribute($attribute);
$options = $attribute_options_model->getAllOptions(false);  
foreach($options as $option)
{
if ($option['label'] == $arg_value)
{
return $option['value'];
}
}  
return false;
}
echo $optionValue = getAttributeOptionValue("diamond_symmetry", "Very Good");
?>

How to add new value in attribute magento ?

<?php
require_once 'app/Mage.php';
umask(0) ;
Mage::app();

$optionValue = addAttributeValue("diamond_symmetry", "Excellent");

function addAttributeValue($arg_attribute, $arg_value)
    {
        $attribute_model        = Mage::getModel('eav/entity_attribute');

        $attribute_code         = $attribute_model->getIdByCode('catalog_product', $arg_attribute);
        $attribute              = $attribute_model->load($attribute_code);

        if(!attributeValueExists($arg_attribute, $arg_value))
        {
            $value['option'] = array($arg_value,$arg_value);
            $result = array('value' => $value);
            $attribute->setData('option',$result);
            $attribute->save();
        }

$attribute_options_model= Mage::getModel('eav/entity_attribute_source_table') ;
        $attribute_table        = $attribute_options_model->setAttribute($attribute);
        $options                = $attribute_options_model->getAllOptions(false);

        foreach($options as $option)
        {
            if ($option['label'] == $arg_value)
            {
                return $option['value'];
            }
        }
       return false;
    }

function attributeValueExists($arg_attribute, $arg_value)
    {
        $attribute_model        = Mage::getModel('eav/entity_attribute');
        $attribute_options_model= Mage::getModel('eav/entity_attribute_source_table') ;

        $attribute_code         = $attribute_model->getIdByCode('catalog_product', $arg_attribute);
        $attribute              = $attribute_model->load($attribute_code);

        $attribute_table        = $attribute_options_model->setAttribute($attribute);
        $options                = $attribute_options_model->getAllOptions(false);

        foreach($options as $option)
        {
            if ($option['label'] == $arg_value)
            {
                return $option['value'];
            }
        }

        return false;
    }
?>

Sunday, April 27, 2014

Magento: Delete All Products Using PhpMyAdmin

SET FOREIGN_KEY_CHECKS = 0;
TRUNCATE TABLE `catalog_product_bundle_option`;
TRUNCATE TABLE `catalog_product_bundle_option_value`;
TRUNCATE TABLE `catalog_product_bundle_selection`;
TRUNCATE TABLE `catalog_product_entity_datetime`;
TRUNCATE TABLE `catalog_product_entity_decimal`;
TRUNCATE TABLE `catalog_product_entity_gallery`;
TRUNCATE TABLE `catalog_product_entity_int`;
TRUNCATE TABLE `catalog_product_entity_media_gallery`;
TRUNCATE TABLE `catalog_product_entity_media_gallery_value`;
TRUNCATE TABLE `catalog_product_entity_text`;
TRUNCATE TABLE `catalog_product_entity_tier_price`;
TRUNCATE TABLE `catalog_product_entity_varchar`;
TRUNCATE TABLE `catalog_product_link`;
TRUNCATE TABLE `catalog_product_link_attribute`;
TRUNCATE TABLE `catalog_product_link_attribute_decimal`;
TRUNCATE TABLE `catalog_product_link_attribute_int`;
TRUNCATE TABLE `catalog_product_link_attribute_varchar`;
TRUNCATE TABLE `catalog_product_link_type`;
TRUNCATE TABLE `catalog_product_option`;
TRUNCATE TABLE `catalog_product_option_price`;
TRUNCATE TABLE `catalog_product_option_title`;
TRUNCATE TABLE `catalog_product_option_type_price`;
TRUNCATE TABLE `catalog_product_option_type_title`;
TRUNCATE TABLE `catalog_product_option_type_value`;
TRUNCATE TABLE `catalog_product_super_attribute_label`;
TRUNCATE TABLE `catalog_product_super_attribute_pricing`;
TRUNCATE TABLE `catalog_product_super_attribute`;
TRUNCATE TABLE `catalog_product_super_link`;
TRUNCATE TABLE `catalog_product_enabled_index`;
TRUNCATE TABLE `catalog_product_website`;
TRUNCATE TABLE `catalog_category_product_index`;
TRUNCATE TABLE `catalog_category_product`;
TRUNCATE TABLE `cataloginventory_stock_item`;
TRUNCATE TABLE `cataloginventory_stock_status`;
TRUNCATE TABLE `cataloginventory_stock`;
INSERT  INTO `catalog_product_link_type`(`link_type_id`,`code`) VALUES (1,'relation'),(2,'bundle'),(3,'super'),(4,'up_sell'),(5,'cross_sell');
INSERT  INTO `catalog_product_link_attribute`(`product_link_attribute_id`,`link_type_id`,`product_link_attribute_code`,`data_type`) VALUES (1,2,'qty','decimal'),(2,1,'position','int'),(3,4,'position','int'),(4,5,'position','int'),(6,1,'qty','decimal'),(7,3,'position','int'),(8,3,'qty','decimal');
INSERT  INTO `cataloginventory_stock`(`stock_id`,`stock_name`) VALUES (1,'Default');
TRUNCATE TABLE `catalog_product_entity`;
SET FOREIGN_KEY_CHECKS = 1;

Saturday, March 29, 2014

Imported products do not show up in frontend

First check this option in Product option
  • are enabled
  • have stock quantity > 0
  • have stock availability = In Stock
  • have visibility = "Catalog, search"
  • have the correct website assigned to them
  • have the right tax class associated with them

Solution 1 : Manage Products > Select All, then select the action Update Attributes and add the products to the correct website(s).
Left side Display this information :  
Products Information
Attributes
Inventory
Websites <-- select this option

And select Main website under the Add Product To Websites 
 

Don't forget to rebuild the indexes.


Solution 2 :
 
<?php
require_once('app/Mage.php');
umask(0);
Mage::app('admin');

$website_ids = array(1, 2); // I'm assuming your website IDs are 1 and 2.

$product_collection = Mage::getModel('catalog/product')->getCollection();
foreach($product_collection as $product) {
    $product->setWebsiteIds($website_ids);
    $product->save();
}
?>
 

Tuesday, March 25, 2014

Format price in the current locale and currency

Unformatted and formatted:
 
$price = $product->getPrice();
$formatted = Mage::helper('core')->currency($price, true, false);

Magento – current store currency details – currency code, currency symbol, currency name

To get the current store currency details eg. Currency code, currency symbol, currency name use the following code.
This code returns the current store currency details.

// store currency code eg. USD, INR
$currency_code = Mage::app()->getStore()->getCurrentCurrencyCode();

// store currency symbol eg. $ 
$currency_symbol = Mage::app()->getLocale()->currency( $currency_code )->getSymbol();

// store currency name eg. Indian Rupee
$currency_name = Mage::app()->getLocale()->currency( $currency_code )->getName();
This code returns the current store currency details. - See more at: http://www.techdilate.com/code/magento-current-store-currency-details-currency-code-currency-symbol-currency-name/#sthash.hwglkaVw.dpuf
This code returns the current store currency details. - See more at: http://www.techdilate.com/code/magento-current-store-currency-details-currency-code-currency-symbol-currency-name/#sthash.hwglkaVw.dpuf
This code returns the current store currency details. - See more at: http://www.techdilate.com/code/magento-current-store-currency-details-currency-code-currency-symbol-currency-name/#sthash.hwglkaVw.dpuf

Tuesday, January 8, 2013

Products Display without Category id in Magento

Products Display without Category id in Magento

require_once ("D:\wamp\www\examples\magento\app\Mage.php");
umask(0);
Mage::app("default");
   
 //////////////  ALL PRODUCTS DISPLAY WITHOUT CATEGORY ID /////////////
    $collection= Mage::getModel('catalog/product')
                        ->getCollection()
                        ->addAttributeToSort('entity_id', 'asc')
                        ->addAttributeToSelect('*')
                        ->setPage(0, 3);// LIMIT BY ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
<table width="100%" border="1">
            <tr>
                <th>Product ID</th>
                <th>Product Name</th>
                <th>SKU</th>
                <th>Price</th>              
                <th>Thumbnail</th>
                <th>Small</th>
                <th>Big</th>
            </tr>
<?php
    foreach ($collection as $product)
    {
        ?>
        <tr>
            <td><?php echo $product->getId();?></td>
            <td><?php echo $product->getName();?></td>
            <td><?php echo $product->getSku();?></td>
            <td><?php echo $product->getPrice();?></td>           
            <td>
                <a href="<?php echo $product->getProductUrl();?>" target="_blank"><img src="<?php echo $product->getThumbnailUrl();?>" /></a>
            </td>
            <td><img src="<?php echo $product->getSmallImageUrl();?>" /></td>
            <td><img src="<?php echo $product->getImageUrl();?>" /></td>
        </tr>
        <?php       
    }
    ?></table>
rathoddhirendra.blogspot.com-Google pagerank and Worth