Pages

Thursday, July 4, 2013

How to sort products Magento

How to change the product position in the category product listing.

Sounds simple but most of people don’t know how to do it.

Magento allows you to order your products by name or by price when you’re surfing a category.

It also allows you to change the position when you’re sorting by default.

    Go to: Catalog -> Manage Categories.
    Select a Category.
    Select the Category Products tab.

>

How to turn on Magento Path Hints

Template Path Hints shows wich file is the frontend using for each part of the page.
Go to System -> Configuration -> Developer
You have to select a specific store view:

Result

How to fast stock update Magento

Create a CSV File

/var/import/updateStockLevels.csv

Place your CSV file like I wrote above.

You can add many fields but I would suggest 2 or 3 (to be faster)
qty
min_qty
use_config_min_qty
is_qty_decimal
backorders
use_config_backorders
min_sale_qty
use_config_min_sale_qty
max_sale_qty
use_config_max_sale_qty
is_in_stock
use_config_notify_stock_qty
manage_stock
use_config_manage_stock
stock_status_changed_automatically
type_id

I will use the SKU and the QTY. My CSV file content looks like:
"sku","qty"
"123456789","10"
Code

Create a PHP file in your root folder with this content.
<?
 define('MAGENTO', realpath(dirname(__FILE__)));
 require_once MAGENTO . '/app/Mage.php';

 umask(0);
 Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
 $count = 0;

 $file = fopen(MAGENTO . '/var/import/updateStockLevels.csv', 'r');
 while (($line = fgetcsv($file)) !== FALSE) {

 if ($count == 0) {
 foreach ($line as $key=>$value) {
 $cols[$value] = $key;
 }
 }

 $count++;

 if ($count == 1) continue;

 #Convert the lines to cols
if ($count > 0) {
 foreach($cols as $col=>$value) {
 unset(${$col});
 ${$col} = $line[$value];
 }
 }

 // Check if SKU exists
 $product = Mage::getModel('catalog/product')->loadByAttribute('sku',$sku);

 if ( $product ) {

 $productId = $product->getIdBySku($sku);
 $stockItem = Mage::getModel('cataloginventory/stock_item')->loadByProduct($productId);
 $stockItemId = $stockItem->getId();
 $stock = array();

 if (!$stockItemId) {
 $stockItem->setData('product_id', $product->getId());
 $stockItem->setData('stock_id', 1);
 } else {
 $stock = $stockItem->getData();
 }

 foreach($cols as $col=>$value) {
 $stock[$col] = $line[$value];
 }

 foreach($stock as $field => $value) {
 $stockItem->setData($field, $value?$value:0);
 }


 $stockItem->save();

 unset($stockItem);
 unset($product);
 }

 echo "<br />Stock updated $sku";

 }
 fclose($file);

?>
Run it and have fun!

You’re done. Please try it your self and fly like a thunder ;)

How to Random Products Home Magento

Create the Home Products file

In my theme I created a copy of the list.phtml called home_list.phtml

/app/design/frontend/base/theme156/template/catalog/product
Show the file in the Home Page

Now we need to show our new file in the Home Page.

Go to your Admin panel -> CMS -> Pages

You should have a page called something like Home. Open it and paste the following code:
{{block type="catalog/product_list" category_id="36" template="catalog/product/home_list.phtml"}}

NOTE: please notice the category_id. It will force to show a certain category. In my case a special one called Home Products.
Shuffle it

The code is quite simple. We need to add the shuffle function after getting all the products.

Look for the getItems() function and past it below.
    <?php $_items = $_productCollection->getItems();
        shuffle($_items); ?>
Break on 3

I added a counter to break the foreach. Something like:
// Show 3 items
$max_items = 3;
$personal_count = 1;

And then at the end:
  if($personal_count == $max_items){break;}
  else{$personal_count++;}
Full Code

Here’s my full code of the home_list.phtml. It will depend on your theme but the suffle part should be the same.
<?php
/**
 * Magento
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Academic Free License (AFL 3.0)
 * that is bundled with this package in the file LICENSE_AFL.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/afl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@magentocommerce.com so we can send you a copy immediately.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade Magento to newer
 * versions in the future. If you wish to customize Magento for your
 * needs please refer to http://www.magentocommerce.com for more information.
 *
 * @category   design_blank
 * @package    Mage
 * @copyright  Copyright (c) 2008 Irubin Consulting Inc. DBA Varien (http://www.varien.com)
 * @license    http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
 */
?>
<?php
/**
 * Product list template
 *
 * @see Mage_Catalog_Block_Product_List
 */
?>
<?php $userIsloggedIn = Mage::getSingleton('customer/session')->isLoggedIn(); ?>
<?php $_productCollection=$this->getLoadedProductCollection() ?>
<?php if(!$_productCollection->count()): ?>
<p class="note-msg"><?php echo $this->__('There are no products matching the selection.') ?></p>
<?php else: ?>
<div style="clear:both;">&nbsp;</div>
<div class="category-products" style="border:none !important;">
  
    <div class="page-indent">   
        <?php // List mode ?>
        <?php if($this->getMode()!='grid'): ?>
        <?php $_iterator = 0; ?>
        <ol class="products-list" id="products-list">
        <?php $list_item=1; foreach ($_productCollection as $_product): ?>
            <li class="item<?php if($list_item==1){echo ' first ';} ?><?php if( ++$_iterator == sizeof($_productCollection) ): ?> last<?php endif; ?>">
                <?php // Product Image ?>
                <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(205, 181); ?>" width="205" height="181" alt="<?php echo $this->htmlEscape($this->getImageLabel($_product, 'small_image')) ?>" title="<?php echo $this->htmlEscape($this->getImageLabel($_product, 'small_image')) ?>" /></a>
  
                <?php // Product description ?>
                <div class="product-shop">
                    <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>
                    <?php if($_product->getRatingSummary()): ?>
                    <?php echo $this->getReviewsSummaryHtml($_product) ?>
                    <?php endif; ?>
                    <?php echo $this->getPriceHtml($_product, true) ?>
                    <?php if($_product->isSaleable()): ?>
                    <p><button class="button" onclick="setLocation('<?php echo $this->getAddToCartUrl($_product) ?>')"><span><span><span><?php echo $this->__('Add to Cart') ?></span></span></span></button></p>
                    <?php else: ?>
                    <?php if ($userIsloggedIn) { ?>
                    <div class="out-of-stock"><?php echo $this->__('Availability: Out of stock.') ?></div>
                    <?php } else { ?>
                    <div class="out-of-stock"><a href="/customer/account/login/">Identificate para poder ver el precio</a></div>
                    <?php } ?>

                  <!--  <p class="availability"><span class="out-of-stock"><?php echo $this->__('Out of stock') ?></span>-->
                    <?php endif; ?>
                    <div class="clear"></div>                   
                </div>
                <div class="clear"></div>
                <div class="desc std">
                    <?php echo nl2br($_product->getShortDescription()) ?>
                    <a href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $this->htmlEscape($_product->getName()) ?>"><?php echo $this->__('Learn More') ?></a>
                </div>
                <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>
            </li>
        <?php $list_item++; endforeach; ?>
        </ol>
        <script type="text/javascript">decorateList('products-list', 'none-recursive')</script>
  
        <?php else: ?>
  
        <?php // Grid Mode ?>
  
        <?php $_collectionSize = $_productCollection->count() ?>
        <table class="products-grid" id="products-grid-table">
        <?php $_columnCount = 3/*$this->getColumnCount()*/; ?>
      
         <?php
            $_items = $_productCollection->getItems();
            shuffle($_items);
        ?>
      
        < ?
            // Show 3 items
            $max_items = 3;
            $personal_count = 1;
        ?>
        <?php $i=0; foreach ($_items as $_product): ?>
      
            <?php if ($i++%$_columnCount==0): ?>
            <tr>
            <?php endif ?>
                <td>
                    <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(205, 181); ?>" width="205" height="181" alt="<?php echo $this->htmlEscape($this->getImageLabel($_product, 'small_image')) ?>" title="<?php echo $this->htmlEscape($this->getImageLabel($_product, 'small_image')) ?>" />
                    </a>                   
                    <?php if($_product->getRatingSummary()): ?>
                    <?php echo $this->getReviewsSummaryHtml($_product, 'short') ?>
                    <?php endif; ?>
                    <?php echo $this->getPriceHtml($_product, true) ?>
                    <?php if($_product->isSaleable()): ?>
                    <button type="button" class="button" onclick="setLocation('<?php echo $this->getAddToCartUrl($_product) ?>')"><span><span><span><?php echo $this->__('Add to Cart') ?></span></span></span></button>
                    <?php else: ?>
                      
                    <?php if ($userIsloggedIn) { ?>
                    <div class="out-of-stock"><?php echo $this->__('Availability: Out of stock.') ?></div>
                    <?php } else { ?>
                    <div class="out-of-stock"><a href="/customer/account/login/">Identificate para poder ver el precio</a></div>
                    <?php } ?>
                  <!--  <p class="availability"><span class="out-of-stock"><?php echo $this->__('Out of stock') ?></span>-->
                    <?php endif; ?>
                    <div class="clear"></div>
                
                </td>
            <?php if ($i%$_columnCount==0 && $i!=$_collectionSize): ?>
            </tr>
            <?php endif ?>
            < ?
               if($personal_count == $max_items){break;}
               else{$personal_count++;}
            ?>
            <?php endforeach ?>
            <?php for($i;$i%$_columnCount!=0;$i++): ?>
                  <td class="empty">&nbsp;</td>
            <?php endfor ?>
            <?php if ($i%$_columnCount==0): ?>
          
            <?php endif ?>
        </table>
        <script type="text/javascript">decorateTable('products-grid-table')</script>
        <?php endif; ?>       
    </div>

</div>
<?php endif; ?>

Magento: Show “track your order” in frontend – My Orders

It is always required for the customer to track their order. The shipping carriers can be anything: Aramex, Bluedart, DHL, First Flight, Federal Express, etc.. Navigate to My Account and place a button in My Orders section there “Track Order”. Paste the code below to link it to tracking popup that you can also see in backend Shipments area.
   

<?php
if($_order->hasShipments()) {
    $show = true;
    foreach($_order->getTracksCollection() as $k=>$v) {                           
        if($v['carrier_code'] == 'custom' || $v['carrier_code'] == '')
            $show = false;
    }
    if($show) {?>
        <span class="separator2">&nbsp;</span>

        <a class="askTrackBtn" href="javascript:;" onclick="popWin('<?php echo Mage::helper('shipping/data')->getTrackingPopUpUrlByOrderId($_order->getId()) ?>', 'tracking the order', 'scrollbars=yes,width=800,height=600,resizable=yes');return false;"><span><?php echo $this->__('Track Order') ?></span></a>
       <?php
    }
}?>

Wednesday, July 3, 2013

Add a New Block to a Magento Template

Go to page.xml and below this:

    <block type="page/html_breadcrumbs" name="breadcrumbs" as="breadcrumbs"/>

Add your new code (e.g.)

    <block type="page/html_lookbookimage" name="lookbookimage" as="lookbookimage"/>

Now, to to /app/code/local/Mage/Page/Block/Html and create a new file called Lookbookimage.php with this code inside:

    <?php
    class Mage_Page_Block_Html_Lookbookimage extends Mage_Core_Block_Template
    {
    function __construct()
    {
    parent::__construct();
    $this->setTemplate('page/html/lookbookimage.phtml');
    }
    }
    ?>

Now create a file, called lookbookimage.phtml in /app/design/frontend/default/YOUR TEMPLATE/template/page/html/

I assume all three steps are required and the names (highlighted) need to match.

Changing the Currency Select Menu in Magento to a List with Flags

ecause a regular select menu can't have images or background images applied to it (except in newer versions of Firefox) you need to use another method by changing a phtml file, css and a touch of JS to make it a touch better.

Step 1: Open /app/design/frontend/default/{YOUR THEME}/template/directory/currency.phtml and change the <select> and everything in between for this:

    <ul>
    <?php foreach ($this->getCurrencies() as $_code => $_name):
    if($_code==$this->getCurrentCurrencyCode()){
    $topoption = '<li style="background-image: url(\'/skin/frontend/default/{YOUR SKIN}/images/flags/'.$_code.'.png\')"><a href="'.$this->getSwitchCurrencyUrl($_code).'">'.$_name.' – '.$_code.'</a></li>'."\n";
    }
    else{
    $otheroptions .= '<li style="background-image: url(\'/skin/frontend/default/{YOUR SKIN}/images/flags/'.$_code.'.png\')"><a href="'.$this->getSwitchCurrencyUrl($_code).'">'.$_name.' – '.$_code.'</a></li>'."\n";
    }
    endforeach;
    echo $topoption.$otheroptions;
    ?>
    </ul>

This makes the options into a list. It also does a few other things – adds the selected class to the chosen currency and moves it to the top each time.

Step 2: You need some flags. Used these (http://graffletopia.com/stencils/355) , but you need to rename the ones you use to match the currency code (e.g. USD.png GBP.png etc.). The upload them to /skin/frontend/default/{YOUR SKIN}/images/flags/ (to match the php above). You will also need to make a downward pointing arrow for the select menu (see css below);

Step 3: You need to add these styles to your css file:

    .block-currency ul{
    padding: 3px;
    background-color: #FFF;
    border: 1px solid #333;
    background-image: url('../images/selectArrow.gif');
    background-position: right top;
    background-repeat: no-repeat;
    }

    .block-currency li{
    background-repeat: no-repeat;
    background-position: left center;
    text-align: left;
    padding-left: 20px;
    display: none;
    font-size: 11px
    }

    .block-currency li:hover{
    background-color: #ebecea;
    }

    .block-currency li.selected{
    display: block;
    }

    .block-currency ul:hover li{
    display: block;
    }

    .block-currency li a{
    text-decoration: none;
    color: #333;
    }

This should do everything you need for it to work. To perfect it there is one final (optional step).

Step 4 (optional): After choosing a currency and before the page reloads the item will revert back to the previously selected item – this might be off putting for a user. The best way to resolve this was to use a bit of JQuery (my framework of choice).

    $j(".block-currency a").click(function(){
    $j(".block-currency li").removeClass("selected");
    $j(this).closest('li').addClass('selected');
    });

All this does is after choosing an item the selected class is removed from all li's in the container and applied to the one just clicked.

Setting the Default Currency for a User in Magento

This won't alter the base price in the system but it will set the start price for a user. Simply add this to the top of /template/directory/currency.phtml

    $currentCurrency = $this->getCurrentCurrencyCode();

    if(!isset($currentCurrency)) $currentCurrency = 'NA';

    $currencies = array("GBP","USD","EUR");

    if(isset($_GET['cy']))
    {
    if (in_array(strtoupper($_GET['cy']),$currencies)) {
    if(strtoupper($_GET['cy']) != $currentCurrency)
    {
    header("Location: ".$this->helper('directory/url')->getSwitchCurrencyUrl()."currency/".$_GET['cy']);
    exit;
    }
    }
    }

Then, you can do something with the domains where a .co.uk site will redirect to the .com with ?cy=GBP at the end.

Get All Child Products in Magento






This script will return all child products from a Magento shop bypassing the category folders. This sample will also take al products shuttle them and return only three.

    require_once 'webshop/app/Mage.php';
    umask(0);
    Mage::app('default');
    $newproducts = array();
    $id = 10; // Id of the category we want to start at
    $cat = Mage::getModel('catalog/category');
    $cat->load($id);
    $products = $cat->getProductCollection();
    $subs = $cat->getAllChildren(true); // Get's all children products (bypassing categories)
    $children = array();
    foreach($subs as $cat_id) {
    $category = new Mage_Catalog_Model_Category();
    $category->load($cat_id);
    $collection = $category->getProductCollection();
    foreach ($collection as $product) {
    $children[] = $product->getId();
    }
    }
    shuffle($children); // Mix them up
    $children = array_slice($children, 0, 3); // Get only 3
    foreach($children as $var => $value)
    {
    $product = Mage::getModel('catalog/product')->load($value);
    echo '<div>
    <a href="webshop/'.str_replace(".html","/",$cat->getUrlPath()).$product->getUrlPath().'"><img src="'.$product->getThumbnailUrl().'" width="55" /></a>
    <p><strong><a href="webshop/'.str_replace(".html","/",$cat->getUrlPath()).$product->getUrlPath().'">'.$product->getName().'</a></strong><br />
    <span>&pound;'.number_format($product->getFinalPrice(),2 ).'</span><br />
    '.$product->getShortDescription().' <a href="webshop/'.str_replace(".html","/",$cat->getUrlPath()).$product->getUrlPath().'">more</a></p>
    <div></div>
    </div>';
    }

Get Current Category Id in Magento

$layer = Mage::getSingleton(‘catalog/layer’);
$_category = $layer->getCurrentCategory();
$currentCategoryId= $_category->getId();