Tuesday, October 1, 2013

RELATED PRODUCTS ON PRODUCT DESCRIPTION PAGE IN MAGENTO

Step 1. Open catalog.xml file for this navigate to the app/design/frontend/default/your_custom_theme/layout/ or you can find this file app/design/frontend/base/default/layout/ open it in the editor of your choice.

Step 2. In catalog.xml search for the catalog_product_view section
<block type="catalog/product_list_related" name="catalog.product.related" before="-" template="catalog/product/list/related.phtml"/>

Step 3. Search for the catalog_product_view section again and copy and paste the code as like given below:
<reference name="content">
<block type="catalog/product_view" name="product.info" template="catalog/product/view.phtml">
<block type="catalog/product_list_related" name="catalog.product.related" as="related" template="catalog/product/list/related.phtml"/>
</block>
</reference>

Step 4. Now navigate to the app/design/frontend/default/your_custom_theme/template/catalog/product/view.phtml or you can find this file app/design/frontend/base/default/template/catalog/product/view.phtml open the file in the editor of your choice, insert the given below code in the desired position where you want to display the related product block in the product description page.
<?php echo $this->getChildHtml('related'); ?>

Step 5. For editing the look of the related products Navigate to the app/design/frontend/default/your_custom_theme/template/catalog/product/list/related.phtml or you can find this file app/design/frontend/base/default/template/catalog/product/list/related.phtml, from here you can change the look and feel of the related products.

Step 6. Now refresh the cache from the Magento admin and delete the browser cache and refresh the page.

Magento add attribute to filter conditions for products collection

General Product Collection:
$collection = Mage::getResourceModel('catalog/product_collection');
$collection->addAttributeToFilter('status',1); //only enabled product
$collection->addAttributeToFilter('visibility',array("neq"=>1)); //except not visible individually
$collection->addAttributeToSelect(array('name','url','small_image')); //add product attribute to be fetched
//$collection->getSelect()->order('rand()');   //uncomment for getting the products in random order
$collection->addStoreFilter();
if(!empty($collection))
{
foreach ($collection as $_product):
echo $_product->getName();   //get product name
endforeach;
}else
{
echo 'There is no products';
}


Get All Products of a category or Product collection filter by the category

$collection = Mage::getResourceModel('catalog/product_collection')
->setStoreId($this->getStoreId())
->addCategoryFilter($category);


$products = Mage::getModel('catalog/product')->getCollection()->addAttributeToSelect(array('name', 'product_url', 'small_image'))->addAttributeToFilter('name', array('like' => 'Nok%'))->load();

a) Equals: eq

$products = Mage::getModel('catalog/product')->getCollection()->addAttributeToSelect(array('name', 'product_url', 'small_image', 'status'))->addAttributeToFilter('status', array('eq' => 1))->load();

b) Not Equals – neq

$products = Mage::getModel('catalog/product')->getCollection()->addAttributeToSelect(array('name', 'product_url', 'small_image','sku'))->addAttributeToFilter('sku', array('neq' => 'test-product'))->load();

c) In – in

$products = Mage::getModel('catalog/product')->getCollection()->addAttributeToSelect(array('name', 'product_url', 'small_image', 'sku')) ->addAttributeToFilter('id', array('in' => array(20,24,100)))->load();

d) Not In – nin

$products = Mage::getModel('catalog/product')->getCollection()->addAttributeToSelect(array('name', 'product_url', 'small_image', 'sku'))->addAttributeToFilter('id', array('nin' => array(20,24,100)))->load();

e) Like – like

$products = Mage::getModel('catalog/product')->getCollection() ->addAttributeToSelect(array('name', 'product_url', 'small_image', 'sku')) ->addAttributeToFilter('name', array('like' => 'Nok%'))->load();

f) Not Like – nlike

$products = Mage::getModel('catalog/product')->getCollection()->addAttributeToSelect(array('name', 'product_url', 'small_image', 'sku')) ->addAttributeToFilter('name', array('nlike' => 'Nok%'))->load();

g) NULL – null

$products = Mage::getModel('catalog/product')->getCollection() ->addAttributeToSelect(array('name', 'product_url', 'small_image', 'sku'))   ->addAttributeToFilter('description', 'null') ->load();

h)  Not NULL – notnull

$products = Mage::getModel('catalog/product')->getCollection()->addAttributeToSelect(array('name', 'product_url', 'small_image', 'sku'))->addAttributeToFilter('description', 'notnull')->load();

i) Greater Than – gt

$products = Mage::getModel('catalog/product')->getCollection()->addAttributeToSelect(array('name', 'product_url', 'small_image', 'sku'))->addAttributeToFilter('id', array('gt' => 10))->load();

j) Less Than – lt

$products = Mage::getModel('catalog/product')->getCollection()->addAttributeToSelect(array('name', 'product_url', 'small_image', 'sku'))->addAttributeToFilter('id', array('lt' => 10))->load();

k) Greater Than or Equals To- gteq

$products = Mage::getModel('catalog/product')->getCollection()->addAttributeToSelect(array('name', 'product_url', 'small_image', 'sku'))->addAttributeToFilter('id', array('gteq' => 20))->load();

l) Less Than or Equals To – lteq

$products = Mage::getModel('catalog/product')->getCollection()->addAttributeToSelect(array('name', 'product_url', 'small_image', 'sku')) ->addAttributeToFilter('id', array('lteq' => 20))->load();

Display All Active Categories

$categories = Mage::getModel('catalog/category')
->getCollection()
->addAttributeToSelect('*')
->addIsActiveFilter();

Display Active Categories Of Any Particular Level in Magento

$categories = Mage::getModel('catalog/category')
->getCollection()
->addAttributeToSelect('*')
->addIsActiveFilter()
->addLevelFilter(1)
->addOrderField('name');

Display Top level categories only in Magento

<?php $_helper = Mage::helper('catalog/category') ?>
<?php $_categories = $_helper->getStoreCategories() ?>
<?php if (count($_categories) > 0): ?>
<ul>
<?php foreach($_categories as $_category): ?>
<li>
<a href="<?php echo $_helper->getCategoryUrl($_category) ?>">
<?php echo $_category->getName() ?>
</a>
</li>
<?php endforeach; ?>
</ul>
<?php endif; ?>

Magento display root categories and subcategories

<?php $_helper = Mage::helper('catalog/category') ?>
<?php $_categories = $_helper->getStoreCategories() ?>
<?php $currentCategory = Mage::registry('current_category') ?>
<?php if (count($_categories) > 0): ?>
    <ul>
    <?php foreach($_categories as $_category): ?>
    <li>
    <a href="<?php echo $_helper->getCategoryUrl($_category) ?>">
    <?php echo $_category->getName() ?> <!--//Top Level Category Listing-->
    </a>
    <?php $_category = Mage::getModel('catalog/category')->load($_category->getId()) ?>
    <?php $_subcategories = $_category->getChildrenCategories() ?>
    <?php if (count($_subcategories) > 0): ?>
    <ul>
    <?php foreach($_subcategories as $_subcategory): ?>
    <li>
    &nbsp;&nbsp;&nbsp;<a href="<?php echo $_helper->getCategoryUrl($_subcategory) ?>"> <!--//Sub Category Listing-->
    <?php echo $_subcategory->getName() ?>
    </a>
    </li>
    <?php endforeach; ?>
    </ul>
    <?php endif; ?>
    </li>
    <?php endforeach; ?>
    </ul>
<?php endif; ?>

Friday, September 27, 2013

Magento print select query for products

To print select query : app\code\core\mage\catalog\model\resources\collection\abstract.php

Monday, September 23, 2013

Magento - Sort by Date Added

copying app/code/core/Mage/Catalog/Block/Product/List.php into app/code/local and adding some sorting code at the end of its _getProductCollection() method:


 / sort by created_at date or entity_id
if(!isset($_GET['order'])) {
    $this->_productCollection->getSelect()->reset( Zend_Db_Select::ORDER );
    $this->_productCollection->getSelect()->order('e.entity_id desc');
}
return $this->_productCollection;

Friday, September 13, 2013

To show the Name of Brands in magento

<div class="brand">
<?php
$product = Mage::getModel('catalog/product');
$attributes = Mage::getResourceModel('eav/entity_attribute_collection')->setEntityTypeFilter($product->getResource()->getTypeId())->addFieldToFilter('attribute_code', 'manufacturer');
$attribute = $attributes->getFirstItem()->setEntity($product->getResource());
$manufacturers = $attribute->getSource()->getAllOptions(false);
?>
<ul id="manufacturer_list"><?php foreach ($manufacturers as $manufacturer): ?>
<li><a href="catalogsearch/advanced/result/?manufacturer[]=<?php echo $manufacturer['value'] ?>"><?php echo $manufacturer['label'] ?></a>
</li>
<?php endforeach; ?>   </ul>
</div>

Product Sold quantity display in your view page in magento.

<?php
$sku = nl2br($_product->getSku());
$_productCollection = Mage::getResourceModel('reports/product_collection')
    ->addOrderedQty()
    ->addAttributeToFilter('sku', $sku)
    ->setOrder('ordered_qty', 'desc')
    ->getFirstItem();
$product = $_productCollection;

echo 'Already sold '.(int)$product->ordered_qty;
?>

Showing the Best Seller Product by code..

Step 1: Create a file app/code/local/Mage/Catalog/Block/Product/Bestseller.php and the following lines of code in it

class Mage_Catalog_Block_Product_Bestseller extends Mage_Catalog_Block_Product_Abstract{
public function __construct(){
parent::__construct();
$storeId = Mage::app()->getStore()->getId();
$products = Mage::getResourceModel('reports/product_collection')
->addOrderedQty()
->addAttributeToSelect('*')
->addAttributeToSelect(array('name', 'price', 'small_image'))
->setStoreId($storeId)
->addStoreFilter($storeId)
->setOrder('ordered_qty', 'desc'); // most best sellers on top
Mage::getSingleton('catalog/product_status')->addVisibleFilterToCollection($products);
Mage::getSingleton('catalog/product_visibility')->addVisibleInCatalogFilterToCollection($products );

$products->setPageSize(3)->setCurPage(1);
$this->setProductCollection($products);
}
}



Step 2: Create a file app/design/frontend/default/YourTheme/template/catalog/product/bestseller.phtml file and add the following lines of code in it

<?php if (($_products = $this->getProductCollection()) && $_products->getSize()): ?>
<div class="page-title">
<h2><?php echo $this->__('Best Seller Products') ?></h2>
</div>
<?php $_collectionSize = count($_products->getItems()) ?>
<table class="products-grid" id="products-grid-table">
<?php $i=1; foreach ($_products->getItems() as $_product): ?>
<?php if ($i%1!==0): ?>
<tr>
<?php endif ?>
<td id="td_<?php echo $i;?>" <?php if($i%3==0 or $i==$_collectionSize){echo 'class="last"';} ?> >
<?php contentBlock('top') ?>
<div id="cont_<?php echo $i;?>">
<h3 class="product-name"><a href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $this->htmlEscape($_product->getName()) ?>"><?php echo $this->htmlEscape($_product->getName()) ?></a></h3>
<a class="product-image" href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $this->htmlEscape($this->getImageLabel($_product, 'small_image')) ?>">
<img src="<?php echo $this->helper('catalog/image')->init($_product, 'small_image')->resize(122, 109); ?>" width="122" height="109" alt="<?php echo $this->htmlEscape($this->getImageLabel($_product, 'small_image')) ?>" title="<?php echo $this->htmlEscape($this->getImageLabel($_product, 'small_image')) ?>" />
</a>
<div class="a-center">
<?php if($_product->getRatingSummary()): ?>
<?php echo $this->getReviewsSummaryHtml($_product, 'short') ?>
<?php endif; ?>
<?php echo $this->getPriceHtml($_product, true) ?>
<?php if($_product->isSaleable()): ?>
<button class="button" onclick="setLocation('<?php echo $this->getAddToCartUrl($_product) ?>')"><span><span><span><?php echo $this->__('Add to Cart') ?></span></span></span></button>
<div class="clear"></div>
<?php else: ?>
<p class="availability"><span class="out-of-stock"><?php echo $this->__('Out of stock') ?></span></p>
<div class="clear"></div>
<?php endif; ?>
<ul class="add-to-links">
<?php if ($this->helper('wishlist')->isAllow()) : ?>
<li><a href="<?php echo $this->helper('wishlist')->getAddUrl($_product) ?>"><?php echo $this->__('Add to Wishlist') ?></a></li>
<?php endif; ?>
<?php if($_compareUrl=$this->getAddToCompareUrl($_product)): ?>
<li class="last"><span class="separator">|</span> <a href="<?php echo $_compareUrl ?>"><?php echo $this->__('Add to Compare') ?></a></li>
<?php endif; ?>
</ul>
<?php if($_product->getevent_date()) {echo $_product->getevent_date();} ?>
</div>
</div>
</td>
<?php if ($i%3==0 or $i==$_collectionSize): ?>
</tr>
<?php endif ?>
<?php $i++; endforeach; $kol = $_collectionSize; ?>
</table>
<?php endif; ?>


Step 3: This above files will create a list of best selling products which can be shown anywhere on your Magento store. All you have to do is place the following line of code block in your template to show the best selling products.

{{block type="catalog/product_bestseller" template="catalog/product/bestseller.phtml"}}

Update products price and special price with sku-simple script in magento

 I am searching with this topic but all I find the paid extension for bulk product updation of price. so I made a simple script to update the product with special price and price through their respective sku.

<?php
/**
 * @author      MagePsycho <info@magepsycho.com>
 * @website     http://www.magepsycho.com
 * @category    Export / Import
 */
$mageFilename = 'app/Mage.php';
require_once $mageFilename;
Mage::setIsDeveloperMode(true);
ini_set('display_errors', 1);
umask(0);
Mage::app('admin');
Mage::register('isSecureArea', 1);
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);

set_time_limit(0);
ini_set('memory_limit','1024M');

/***************** UTILITY FUNCTIONS ********************/
function _getConnection($type = 'core_read'){
    return Mage::getSingleton('core/resource')->getConnection($type);
}

function _getTableName($tableName){
    return Mage::getSingleton('core/resource')->getTableName($tableName);
}

function _getAttributeId($attribute_code = 'price'){
    $connection = _getConnection('core_read');
    $sql = "SELECT attribute_id
                FROM " . _getTableName('eav_attribute') . "
            WHERE
                entity_type_id = ?
                AND attribute_code = ?";
    $entity_type_id = _getEntityTypeId();
    return $connection->fetchOne($sql, array($entity_type_id, $attribute_code));
}
function _getAttributeId1($attribute_code = 'special_price'){
    $connection = _getConnection('core_read');
    $sql = "SELECT attribute_id
                FROM " . _getTableName('eav_attribute') . "
            WHERE
                entity_type_id = ?
                AND attribute_code = ?";
    $entity_type_id1 = _getEntityTypeId();
    return $connection->fetchOne($sql, array($entity_type_id1, $attribute_code));
}

function _getEntityTypeId($entity_type_code = 'catalog_product'){
    $connection = _getConnection('core_read');
    $sql        = "SELECT entity_type_id FROM " . _getTableName('eav_entity_type') . " WHERE entity_type_code = ?";
    return $connection->fetchOne($sql, array($entity_type_code));
}

function _getIdFromSku($sku){
    $connection = _getConnection('core_read');
    $sql        = "SELECT entity_id FROM " . _getTableName('catalog_product_entity') . " WHERE sku = ?";
    return $connection->fetchOne($sql, array($sku));

}


function _checkIfSkuExists($sku){
    $connection = _getConnection('core_read');
    $sql        = "SELECT COUNT(*) AS count_no FROM " . _getTableName('catalog_product_entity') . " WHERE sku = ?";
    $count      = $connection->fetchOne($sql, array($sku));
    if($count > 0){
        return true;
    }else{
        return false;
    }
}

function _updatePrices($data){
    $connection     = _getConnection('core_write');
    $sku            = $data[0];
    $newPrice       = $data[1];
 $specialPrice   = $data[2];
    $productId      = _getIdFromSku($sku);
    $attributeId    = _getAttributeId();
 $attributeId1    = _getAttributeId1();

    $sql = "UPDATE " . _getTableName('catalog_product_entity_decimal') . " cped
                SET  cped.value = ?
            WHERE  cped.attribute_id = ?
            AND cped.entity_id = ?";
$sql1 = "UPDATE " . _getTableName('catalog_product_index_price') . " cpip
                SET  cpip.final_price = ?
            WHERE cpip.entity_id = ?";


    $connection->query($sql, array($newPrice, $attributeId, $productId));
 $connection->query($sql, array($specialPrice, $attributeId1, $productId));
 $connection->query($sql1, array($specialPrice, $productId));

}

/***************** UTILITY FUNCTIONS ********************/

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

$message = '';
$count   = 2;
foreach($data as $_data){
    if(_checkIfSkuExists($_data[0])){
        try{
            _updatePrices($_data);
            $message .= $count . '> Success:: While Updating Price (' . $_data[1] . ') of Sku (' . $_data[0] . '). <br />';
_updatePrices($_data);
            $message .= $count . '> Success:: While Updating Price (' . $_data[2] . ') of Sku (' . $_data[0] . '). <br />';

        }catch(Exception $e){
            $message .=  $count .'> Error:: While Upating  Price (' . $_data[1] . ') of Sku (' . $_data[0] . ') => '.$e->getMessage().'<br />';
$message .=  $count .'> Error:: While Upating  Price (' . $_data[2] . ') of Sku (' . $_data[0] . ') => '.$e->getMessage().'<br />';
        }
    }else{
        $message .=  $count .'> Error:: Product with Sku (' . $_data[0] . ') does\'t exist.<br />';
    }
    $count++;
}
echo $message;
?>



save this script to your root file and run it...
and for csv your field should be:

sku    price   special_price



The csv save in var/import/prices.csv
Note:- prices.csv is the name of csv file.

Reindexing of Product Flat Data in magento:

You have to truncate all the 'catalog_product_flat_i' table:
where 'i' can be 1,2,3,4,....

In my case there are 3 table so i fire this query to my phpmyadmin:
TRUNCATE `catalog_product_flat_1`;
TRUNCATE `catalog_product_flat_2`;
TRUNCATE `catalog_product_flat_3`;

How to increase page speed in magento:('without merge css and javascript files')

In you htaccess file do chages as:

Uncomment the line
 php_flag zlib.output_compression on
means remove '#' from starting of php_flag zlib.output_compression on.

write these line in your htaccess file

<IfModule mod_expires.c>

# Enable expirations

ExpiresActive On

# Default directive

ExpiresDefault "access plus 1 year"

# My favicon

ExpiresByType image/x-icon "access plus 1 year"

# Images

ExpiresByType image/gif "access plus 1 year"

ExpiresByType image/png "access plus 1 year"

ExpiresByType image/jpg "access plus 1 year"

ExpiresByType image/jpeg "access plus 1 year"

# CSS

ExpiresByType text/css "access 1 year"

# Javascript

ExpiresByType application/javascript "access plus 1 year"

</IfModule>


Uncomment the lines:

SetOutputFilter DEFLATE
AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css text/javascript
BrowserMatch ^Mozilla/4 gzip-only-text/html
BrowserMatch ^Mozilla/4\.0[678] no-gzip
BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
SetEnvIfNoCase Request_URI \.(?:gif|jpe?g|png)$ no-gzip dont-vary
Header append Vary User-Agent env=!dont-vary


means remove '#' from starting of these lines.

How to overwrite magento controller in local directory

For Example you have to overwrite Mage/Contacts/controller/IndexController.php
Step 1: First you have to make a xml in app/etc/modules/ with name CompanyName_NameSpace.xml true local 0.1.0

Step2: You have to create the folders if not exist in local/CompanyName/NameSpace/etc/ local/CompanyName/NameSpace/controllers/ In etc folder you have to create a config.xml file Shweta_Newscontacts In controllers folder copy the Mage/Contacts/controller/IndexController.php file and include the lines: include_once('Mage/Contacts/controllers/IndexController.php'); and change the class name as: class CompanyName_NameSpace_IndexController extends Mage_Core_Controller_Front_Action Now apply changes in the file you wanted. Now also, Magento take local pool file instead of core pool.