Pages

Friday 28 November 2014

Magento Category image resize

1-Copy category folder from base/default/template/catalog/category and paste it in your theme before modification.
2-copy and paste the following code in your-theme/default/template/catalog/category/view.phtml
$_file_name = $_category->getThumbnail();             
$_media_dir = Mage::getBaseDir('media') . DS . 'catalog' . DS . 'category' . DS;
$cache_dir = $_media_dir . 'resize' . DS;

if (file_exists($cache_dir . $_file_name)) {
$_categoryImg =Mage::getBaseUrl('media') .  'catalog' . DS . 'category' . DS . 'resize' . DS . $_file_name;
} elseif (file_exists($_media_dir . $_file_name)) {
if (!is_dir($cache_dir)) {
mkdir($cache_dir);
}

$_image = new Varien_Image($_media_dir . $_file_name);
$_image->constrainOnly(true);
$_image->keepAspectRatio(false);
$_image->keepFrame(false);
$_image->keepTransparency(true);
$_image->resize(500, 500); // change image height, width
$_image->save($cache_dir . $_file_name);
$_categoryImg = Mage::getBaseUrl('media') . 'catalog' . DS . 'category' . DS . 'resize' . DS . $_file_name;
}
//echo  $_categoryImg ; // display resize category thumbnail imagename

Thursday 27 November 2014

Magento Remove all Customers with Reset Id

Run Below Query in your database.please make a backup your db
SET FOREIGN_KEY_CHECKS=0;
-- reset customers
TRUNCATE customer_address_entity;
TRUNCATE customer_address_entity_datetime;
TRUNCATE customer_address_entity_decimal;
TRUNCATE customer_address_entity_int;
TRUNCATE customer_address_entity_text;
TRUNCATE customer_address_entity_varchar;
TRUNCATE customer_entity;
TRUNCATE customer_entity_datetime;
TRUNCATE customer_entity_decimal;
TRUNCATE customer_entity_int;
TRUNCATE customer_entity_text;
TRUNCATE customer_entity_varchar;
TRUNCATE log_customer;
TRUNCATE log_visitor;
TRUNCATE log_visitor_info;

ALTER TABLE customer_address_entity AUTO_INCREMENT=1;
ALTER TABLE customer_address_entity_datetime AUTO_INCREMENT=1;
ALTER TABLE customer_address_entity_decimal AUTO_INCREMENT=1;
ALTER TABLE customer_address_entity_int AUTO_INCREMENT=1;
ALTER TABLE customer_address_entity_text AUTO_INCREMENT=1;
ALTER TABLE customer_address_entity_varchar AUTO_INCREMENT=1;
ALTER TABLE customer_entity AUTO_INCREMENT=1;
ALTER TABLE customer_entity_datetime AUTO_INCREMENT=1;
ALTER TABLE customer_entity_decimal AUTO_INCREMENT=1;
ALTER TABLE customer_entity_int AUTO_INCREMENT=1;
ALTER TABLE customer_entity_text AUTO_INCREMENT=1;
ALTER TABLE customer_entity_varchar AUTO_INCREMENT=1;
ALTER TABLE log_customer AUTO_INCREMENT=1;
ALTER TABLE log_visitor AUTO_INCREMENT=1;
ALTER TABLE log_visitor_info AUTO_INCREMENT=1;
SET FOREIGN_KEY_CHECKS=1;

Tuesday 25 November 2014

Magento add custom field in newsletter module.

Step 1 : Open file: root/app/design/frontend/your-package-name/your-theme/template/newsletter/subscribe.phtml

Add input field for ‘Name’ before ‘Email’ Field : 
 

Step 2 : Open file: root/app/code/core/Mage/Newsletter/controllers/SubscriberController.php

A. Search:
 $status = Mage::getModel('newsletter/subscriber')->subscribe($email);
Replace with:
 if ($this->getRequest()->getPost('subscriber_name'))
{
$subscriber = Mage::getModel('newsletter/subscriber')->loadByEmail($email);
$subscriber_name     = (string) $this->getRequest()->getPost('subscriber_name');
$subscriber->setsubscriber_name($subscriber_name);
}
$status = Mage::getModel('newsletter/subscriber')->subscribe($email,$subscriber_name);
Step 3 : Open file : root/app/code/core/Mage/Newsletter/Model/Subscriber.php

A. Search:
 public function subscribe($email)
Replace with:
 public function subscribe($email,$subscriber_name=null)
B. Search:
 $this->setSubscriberEmail($email);
Add after it:
 $this->setsubscriber_name($subscriber_name);
C. Search:
 public function setEmail($value)
{
return $this->setSubscriberEmail($value);
}
Add after it:
 public function setsubscriber_name($value)
{
return $this->setSubscriberName($value);
}
Step 4 : Open file : root/app/code/core/Mage/Adminhtml/Block/Newsletter/Subscriber/Grid.php
A. Search:
 $this->addColumn('email', array(
'header'    => Mage::helper('newsletter')->__('Email'),
'index'     => 'subscriber_email'
));
Add before it:
 $this->addColumn('subscriber_name', array(
'header'    => Mage::helper('newsletter')->__('Subscriber Name'),
'index'     => 'subscriber_name',
'default'   =>    '----'
));
Step 5 : Open your database.
 Create a field ‘subscriber_name’ in table “Newsletter Subscriber”.
Step 6 : Clear the caches ............ and reindex

Wednesday 19 November 2014

Magento change the newsletter validation message

1- In your root folder\js\prototype\validation.js

2-Open the above file and find it (validate-email) in magento 1.9 near line 526 change it according to your requirement.

Wednesday 12 November 2014

Magento To get the total product under the particular category(product count)

<?php
    $prodCollection = Mage::getResourceModel('catalog/product_collection')->addCategoryFilter($child);
    
    echo $prodCollection->count(); ?>

Magento subcategory from a particular category

<?php
    $_categoryModel = new Mage_Catalog_Model_Category();
    
    $_subCategoryList = $_categoryModel->load(3)->getChildrenCategories();
    
    foreach ($_subCategoryList as $category)
    {
        $cat=$_categoryModel->load($category->getId());
?>
        <li><div><img src="<?php echo Mage::getBaseUrl('media').'catalog/category/'.$cat->getImage()?>"/><a href="#"><?php echo $cat->getName()?></a></div></li>
<?php
        print_r($category);
    }
?>

Magento subcategory from the parent category

<?php
        $allCats = Mage::getModel('catalog/category')->getCollection()->addAttributeToSelect('*');
        
        foreach($allCats as $category)
        {
            if($category->getParentId() ==  Mage::app()->getStore()->getRootCategoryId() && $category->getIsActive()) // it'll check the root category
            {
                $subcats = $category->getChildren();
                $total_cat_array=explode(',',$subcats);
                foreach($total_cat_array as $subId)
                {
                    $child = Mage::getModel('catalog/category')->load($subId);
                    echo $child->getName();
                }
            }
        }      
  ?>

Magento Add to cart button on upsell products in product detail page

To add a Add to Cart button on upsell products in product detail pages, first open the upsell.phtml file located in app/design/frontend/your_package/your_theme/template/catalog/product/list/ that caused for these upsell products list.

Then add a new form with Add to Cart button & quantity input box inside the loop that generate upsell products.
<form action="<?php echo $this->getAddToCartUrl($_link) ?>" method="post" id="product_addtocart_form_<?php echo $_link->getId()?>"<?php if($_link->getOptions()): ?> enctype="multipart/form-data"<?php endif; ?>>

      <?php if(!$_link->isGrouped()): ?>
      <input type="text" name="qty" id="qty" maxlength="12" value="<?php echo ($this->getMinimalQty($_link)?$this->getMinimalQty($_link):20) ?>" />
      <label for="qty"><?php echo $this->__('Qty') ?>:</label>
      <?php endif; ?>
      <button type="button" onclick="this.form.submit()"><span><span><span><?php echo $this->__('Add to Cart') ?></span></span></span></button>

</form>

Magento Category listing under default category

<?php
$category = Mage::getModel('catalog/category')->getCategories(2);
    foreach($category as $_category){

    $currentCat = Mage::getModel('catalog/category')->load($_category->getId()); ?>
     <a href="<?php echo $currentCat->getUrl(); ?>"><span><?php echo $currentCat->getName()?></span></a><br/>
         <?php
        }
?>

Magento Left Category with jquery

<div class="left-category"><?php echo $this-> __('CATEGORIES')?></div>



<div class="maincategory">
<?php

    $_helper = Mage::helper('catalog/category'); 
    $_categories = $_helper->getStoreCategories(); 
    $currentCategory = Mage::registry('current_category') ;
    
    $rootCategoryId = Mage::app()->getStore()->getRootCategoryId();
    $rootCategory = Mage::getModel('catalog/category')->load($rootCategoryId);
    
    $childIds = explode(',',$rootCategory->getChildren());
    
    if (count($childIds) > 0):

?>
    
    <?php foreach($childIds as $_category):
    $_category = Mage::getModel('catalog/category')->load($_category);
    ?>
    

    
<div class="maincatdiv">
    <div class="catheader">
<span class="category_name">
<a href="<?php echo $_helper->getCategoryUrl($_category) ?>">
<?php echo $_category->getName() ?></a></span>
<?php if ($_category->getChildren() != ''){?><span class="caticon">+</span><?php } ?>
    </div>
    <div class="catcontent" style="display:none;"><?php
    
if ($_category->getChildren() != ''): 
    
$allsubchild = explode(',',$_category->getChildren());
    ?>
<ul>
<?php foreach($allsubchild as $_sub):
$_subcategory = Mage::getModel('catalog/category')->load($_sub);
?>
    <li>

<a href="<?php echo $_helper->getCategoryUrl($_subcategory) ?>">
<?php echo $_subcategory->getName() ?>
</a>
    </li>
<?php endforeach; ?>
</ul>
    <?php endif; ?></div>
</div>
    
    <?php endforeach; ?>
    
<?php endif; ?>
</div>

<script type="text/javascript">
jQuery(window).load(function(){
    jQuery('.caticon').click(function(){
var str = jQuery(this).closest('.maincatdiv').find('.catcontent').html().split(' ');
if(str[0] != '')
{
    if(jQuery(this).attr('class').indexOf('active') != -1)
    {
jQuery('.catcontent').slideUp();
jQuery('.caticon').removeClass('active');
jQuery('.caticon').html('+');
    }
    else{

jQuery('.catcontent').slideUp();
jQuery('.caticon').removeClass('active');
jQuery('.caticon').html('+');
jQuery(this).addClass('active');
jQuery(this).html('-');
jQuery(this).closest('.maincatdiv').find('.catcontent').slideDown();
    
    }
}

    });
})
</script> 

Magento product slider

1-place the jquery.bxslider folder in magento root js folder.
From: http://bxslider.com/examples/carousel-dynamic-number-slides
2-And place the following code. in your product collection page For jquery:
-----------------------------------------------------------------------------------------------------------------------
<link rel="stylesheet" href="<?php echo $this->getJsUrl()?>jquery.bxslider/jquery.bxslider.css" type="text/css" />
<script src="<?php echo $this->getJsUrl()?>jquery.bxslider/jquery.bxslider.js"></script>
<script type="text/javascript">
jQuery(window).load(function(){
jQuery('.bxslider').bxSlider({
pager:false,
minSlides: 3,
maxSlides: 5,
slideWidth: 240,
slideMargin:10
});
})
</script> 
--------------------------------------------------------------------------------------
For product collection:
<!-- for related product-->    
<div class="block block-related block-related-thumbnails">
<div class="also-bought"><h2 class="section-title padding-right "><?php echo $this->__('CUSTOMER WHO BOUGHT THIS ITEAM ALSO BOUGHT'); ?></h2></div>

<ul class="bxslider">    
<?php
$_productCollection = Mage::getModel('catalog/product')->getCollection();                              
$_productCollection->addAttributeToFilter('status', 1); //enabled
$_productCollection->addAttributeToFilter('visibility', 4); //catalog, search
$_productCollection->getSelect()->order(new Zend_Db_Expr('RAND()'));
$_productCollection->setOrder('name', 'ASC');
$_productCollection->getSelect()->limit(10);

?>
<?php  
foreach ($_productCollection as $_product)
{
$model = Mage::getModel('catalog/product');
$product_id = $_product->getId();
$_product = $model->load($product_id);
//echo $_product->getPrice()."<br>";
//echo $_product->getName()."<br>";
$_image=Mage::getModel('catalog/product')->load($product_id);
//echo Mage::helper('catalog/image')->init($_image, 'image')."<br>";
?>
<li><div class="also-bought-product">
<div class="also-bought-product-image"><a href="<?php echo $_product->getProductUrl() ?>"><img src="<?php echo Mage::helper('catalog/image')->init($_image, 'image')->resize(200,150); ?>"></a></div>
<div class="also-bought-product-name"><?php echo $_product->getName(); ?></div>
<?php $actualprice= Mage::helper('core')->currency($_product->getPrice(),true,false);//with currency symbol
$specialprice= Mage::helper('core')->currency($_product->getSpecialPrice(),true,false);//with currency symbol
$actual_Price = $_product->getPrice();
$special_price = Mage::getModel('catalog/product')->load($_product->getId())->getSpecialPrice(); // Get the Special Price without currency
$specialPriceFromDate = Mage::getModel('catalog/product')->load($_product->getId())->getSpecialFromDate();// Get the Special Price FROM date
$specialPriceToDate = Mage::getModel('catalog/product')->load($_product->getId())->getSpecialToDate();// Get the Special Price TO date
$today =  time();// Get Current date ?>
<?php
if ($special_price): ?>
<div class="custom-product-div">
<?php
if ($special_price):
if($today >= strtotime( $specialPriceFromDate) && $today <= strtotime($specialPriceToDate) || $today >= strtotime( $specialPriceFromDate) && is_null($specialPriceToDate)): ?>
<div class="special-price"><?php echo $specialprice; ?></div>
<?php  
endif;
endif;?>        
<div class="actual-price"><?php echo $actualprice; ?></div>
<?php
if ($special_price):
if($today >= strtotime( $specialPriceFromDate) && $today <= strtotime($specialPriceToDate) || $today >= strtotime( $specialPriceFromDate) && is_null($specialPriceToDate)): ?>
<?php // Discount percents output start ?>
<?php if($special_price < $actual_Price ): ?>
<?php $_savePercent = 100 - round(($special_price / $actual_Price)*100); ?>
<p class="special-price yousave">
<span class="price"><?php echo $_savePercent; ?>% <span>OFF</span></span>
</p>
<?php endif; ?>
<?php // Discount percent output end ?>
<?php  
endif;
endif;?>
</div>
<?php else :?>
<div class="custom-product-div"><div class="actualprice"><?php echo $actualprice; ?></div></div>
<?php endif;?>
</div></li>
<?php    
}                                     
?>
</ul>
</div>

Social Plugin facebook like, twitter , pintrest, google+

<!-- facebook like button start -->
<iframe src="//www.facebook.com/plugins/like.php?href=<?php echo Mage::helper('core/url')->getCurrentUrl(); ?>&amp;width&amp;layout=button_count&amp;action=like&amp;show_faces=false&amp;share=false&amp;height=21&amp;appId=<?php //echo Mage::getStoreConfig('facebookfree/settings/appid'); ?>" scrolling="no" frameborder="0" style="border:none; overflow:hidden; height:21px;" allowTransparency="true"></iframe>
<!-- facebook like button end -->

<!-- twitter button script start-->
<script type="text/javascript">
window.twttr=(function(d,s,id){var t,js,fjs=d.getElementsByTagName(s)[0];if(d.getElementById(id)){return}js=d.createElement(s);js.id=id;js.src="https://platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);return window.twttr||(t={_e:[],ready:function(f){t._e.push(f)}})}(document,"script","twitter-wjs"));
</script>
<!-- twitter button script end-->
<!-- twitter share button start -->
<a class="twitter-share-button" href="https://twitter.com/share" data-count="none">Tweet</a>
<!-- twitter share button end -->

<!-- google + start    -->
<span class="googleplus">
<a href="https://plus.google.com/share?url=<?php echo $_product->getProductUrl(); ?>" target="_blank" >
<img src="<?php echo $this->getSkinUrl(); ?>images/gplus.jpg" alt="Google+" title="Google+"/>
</a>
</span>
<!-- google + end    -->

<!-- pintrest start-->
<?php
$_pinlink['url'] = $_product->getProductUrl();                      
$_pinlink['media'] = $this->helper('catalog/image')->init($_product, 'image')->__toString() ;
$_pinlink['description'] = $_helper->productAttribute($_product, $_product->getName(), 'name') . " - " . strip_tags($_product->getDescription());                                                                                   
?>
<a href="http://pinterest.com/pin/create/button/?<?php echo http_build_query($_pinlink) ?>" class="pin-it-button" count-layout="horizontal"></a>                    
<script type="text/javascript" src="//assets.pinterest.com/js/pinit.js"></script>
<!-- pintrest end→

Magento Pincode varification to add to cart.

1- Take the html layout where you want to the html layout.
<div class="pincode">
<input type="text" name="pincode" id='pincode1'  placeholder="Enter pincode to check dilivery option">
<div id='pincode'></div>
<input class="verify-button" type='button' onclick="checkForm()" value='Verify'>
</div>

2- The jquery for validation.
<script type="text/javascript">
function checkForm()
{
    //fetching value from input field pincode  and storing it in a variable
    var pincode = document.getElementById("pincode1").value;
    //alert(pincode);
    //Check input Fields Should not be blanks.
    if (pincode == '' )  
    {
        jQuery('#pincode').html('<div style="color:red;">Enter The Pincode</div>');
    }
    else
    {
        jQuery.ajax({
            url: "<?php echo $this->getBaseUrl();?>ajax/pincode_verify.php",
            type: "POST",
            data:'pincode='+pincode,
            success: function(abc){
            //alert(abc);
                if(abc==1){
                    jQuery(".add-to-box").show();
                    jQuery('#pincode').html('<div style="color:green;">This pincod is available</div>');
                }
                else{
                    jQuery(".add-to-box").hide();
                    jQuery('#pincode').html('<div style="color:red;">This pincod is not available</div>');
    
                }  
            }
        });
    }
}
</script>

3- create a folder name ajax in magento root directory and the inside it the pincode_verify.php for validation.
<?php
require_once '../app/Mage.php';
Mage::app('default');

extract($_REQUEST);
$read = Mage::getSingleton( 'core/resource' )->getConnection( 'core_read' );
$available_pincodes = Mage::getSingleton( 'core/resource' )->getTableName( 'available_pincodes' );
$query = "SELECT * FROM " . $available_pincodes." WHERE pincode_value = '".$pincode."'" ;
$result = $read->fetchAll( $query );

if(count($result) > 0)
echo 1;
else
echo 0;
?>

Magento custom sql Query

$read = Mage::getSingleton( 'core/resource' )->getConnection( 'core_read' );
        $pincode = Mage::getSingleton( 'core/resource' )->getTableName( 'available_pincodes' );
        $query = "SELECT * FROM " . $pincode ;
        $result = $read->query( $query );
        while ( $row = $result->fetch() ) {
        echo 'Pincode ID: ' . $row['pincode_value'] . '<br>';
        }
        ?>

Magento product status (in stock/out of stock)

$stock = $product->getStockItem();
if ($stock->getIsInStock()) {
   echo "product is in stock";
} else {
   echo "product is not in stock";
}

Magento Class For Every 5th element

1- Take a variable and assign to 0. like
<?php $counter=0; ?>
2- And give the condition in the li tag as follows.
<li class="product <?php if($counter%5==4): echo "last";  endif;?>"> // for fifth element

Magento On sale product listing by category

1-Create a new CMS page with content set to…
{{block type="catalog/product_list" template="onsale/sale.phtml"}}

2- and a template for listing your products
 app/design/frontend/default/YOUR_THEME/template/inchoo/onsale/sale.phtml
<?php
$_productCollection = Mage::getModel('catalog/product')->getCollection();
$_productCollection->addAttributeToSelect(array(
                                   'image',
                                   'name',
                                   'short_description'
                   ))
                   ->addFieldToFilter('visibility', array(
                               Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH,
                               Mage_Catalog_Model_Product_Visibility::VISIBILITY_IN_CATALOG
                   )) //showing just products visible in catalog or both search and catalog
                   ->addFinalPrice()
//                        ->addAttributeToSort('price', 'asc') //in case we would like to sort products by price
                   ->getSelect()
                   ->where('price_index.final_price < price_index.price')
//                        ->limit(30) //we can specify how many products we want to show on this page
//                        ->order(new Zend_Db_Expr('RAND()')) //in case we would like to sort products randomly
                   ;
 
Mage::getModel('review/review')->appendSummary($_productCollection);
 
$_helper = $this->helper('catalog/output');
?>
//
<?php if(!$_productCollection->count()): ?>
    <p class="note-msg"><?php echo $this->__('There are no products matching the selection.') ?></p>
<?php else: ?>
    <div class="category-products">
        <?php // List mode ?>
            <?php $_iterator = 0; ?>
            <ol class="products-list" id="products-list">
                <?php foreach ($_productCollection as $_product): ?>
                    <li class="item<?php if( ++$_iterator == sizeof($_productCollection) ): ?> last<?php endif; ?>">
                        <?php // Product Image ?>
                        <a href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $this->stripTags($this->getImageLabel($_product, 'small_image'), null, true) ?>" class="product-image"><img src="<?php echo $_product->getImageUrl(); ?>" width="135" height="135" alt="<?php echo $this->stripTags($this->getImageLabel($_product, 'small_image'), null, true) ?>" /></a>
                        <?php // Product description ?>
                        <div class="product-shop">
                            <div class="f-fix">
                                <?php $_productNameStripped = $this->stripTags($_product->getName(), null, true); ?>
                                <h2 class="product-name"><a href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $_productNameStripped; ?>"><?php echo $_helper->productAttribute($_product, $_product->getName() , 'name'); ?></a></h2>
                                <?php if($_product->getRatingSummary()): ?>
                                    <?php echo $this->getReviewsSummaryHtml($_product) ?>
                                <?php endif; ?>
                                <?php echo $this->getPriceHtml($_product, true) ?>
                                <?php if($_product->isSaleable()): ?>
                                    <p><button type="button" title="<?php echo $this->__('Add to Cart') ?>" class="button btn-cart" onclick="setLocation('<?php echo $this->getAddToCartUrl($_product) ?>')"><span><span><?php echo $this->__('Add to Cart') ?></span></span></button></p>
                                <?php else: ?>
                                    <p class="availability out-of-stock"><span><?php echo $this->__('Out of stock') ?></span></p>
                                <?php endif; ?>
                                <div class="desc std">
                                    <?php echo $_helper->productAttribute($_product, $_product->getShortDescription(), 'short_description') ?>
                                    <a href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $_productNameStripped ?>" class="link-learn"><?php echo $this->__('Learn More') ?></a>
                                </div>
                                <ul class="add-to-links" style="margin:0; padding-left:0; list-style: none;">
                                    <?php if ($this->helper('wishlist')->isAllow()) : ?>
                                        <li><a href="<?php echo $this->helper('wishlist')->getAddUrl($_product) ?>" class="link-wishlist"><?php echo $this->__('Add to Wishlist') ?></a></li>
                                    <?php endif; ?>
                                    <?php if($_compareUrl=$this->getAddToCompareUrl($_product)): ?>
                                        <li><span class="separator">|</span> <a href="<?php echo $_compareUrl ?>" class="link-compare"><?php echo $this->__('Add to Compare') ?></a></li>
                                    <?php endif; ?>
                                </ul>
                            </div>
                        </div>
                    </li>
                <?php endforeach; ?>
            </ol>
            <script type="text/javascript">decorateList('products-list', 'none-recursive')</script>
    </div>
<?php endif; ?>

3-Create a Category(On Sale) and call the static block in the category. 
1- create category on sale.
2- inside category go to Display setting select display mode to static block only.
3-And select the on sale cms block you created.
 

Magento Get custom textarea attribute field if available

<?php if ($_product->getWhatsincluded()): ?>// what is included is custom textarea attribute.
  <?php echo $_helper->productAttribute($_product, $_product->getwhatsincluded(), 'whatsincluded') ?>
  <?php endif;?>

Magento Get Product Msrp if available.

<?php if ($_product->getMsrp()):  ?>
<div class="mrp"><span class="mrp-price"><?php echo $this->__('MRP'); ?>:</span><span class="mrsp-price"><?php echo $mrp; ?></span></div>
<?php endif; ?>

Monday 10 November 2014

Magento Remove Decimals from product price


For this, you need to edit /app/code/core/Mage/Directory/Model/Currency.php

Note:- Do not change core functionality beside override the function in local folder
Find the following :- code
public function format($price, $options=array(), $includeContainer = true, $addBrackets = false)
    {
return $this->formatPrecision($price, 2, $options, $includeContainer, $addBrackets);
    }
change this code to:-
public function format($price, $options=array(), $includeContainer = true, $addBrackets = false)
    {
return $this->formatPrecision($price, 0, $options, $includeContainer, $addBrackets);
    }

Magento Sale icon if special price available

Open app/design/frontend/YourPackage/YourTheme/template/catalog/list.phtml Find (around line 96)
<a href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $this->stripTags($this->getImageLabel($_product, 'small_image'), null, true) ?>" class="product-image">

<img src="<?php echo $this->helper('catalog/image')->init($_product, 'small_image')->resize(135); ?>" width="135" height="135" alt="<?php echo $this->stripTags($this->getImageLabel($_product, 'small_image'), null, true) ?>" />

</a>
change to
<a href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $this->stripTags($this->getImageLabel($_product, 'small_image'), null, true) ?>" class="product-image">

<img src="<?php echo $this->helper('catalog/image')->init($_product, 'small_image')->resize(135); ?>" width="135" height="135" alt="<?php echo $this->stripTags($this->getImageLabel($_product, 'small_image'), null, true) ?>" />

<?php 

    // Get the Special Price

    $specialprice = Mage::getModel('catalog/product')->load($_product->getId())->getSpecialPrice(); 

    // Get the Special Price FROM date

    $specialPriceFromDate = Mage::getModel('catalog/product')->load($_product->getId())->getSpecialFromDate();

    // Get the Special Price TO date

    $specialPriceToDate = Mage::getModel('catalog/product')->load($_product->getId())->getSpecialToDate();

    // Get Current date

    $today =  time();

    if ($specialprice):

        if($today >= strtotime( $specialPriceFromDate) && $today <= strtotime($specialPriceToDate) || $today >= strtotime( $specialPriceFromDate) && is_null($specialPriceToDate)):

?>

        <img src="path/to/sale-icon.png" width="50" height="50" class="onsaleicon" />

<?php  

        endif;

    endif;

?>

</a>
Next open style.css (skin/frontend/YourPackage/YourTheme/css/style.css)Find
.products-grid .product-image { display:block; width:135px; height:135px; margin:0 0 10px; }
change to
.products-grid .product-image { display:block; width:135px; height:135px; margin:0 0 10px; position:relative;}
Below this add
.onsaleicon{position:absolute; top:0; right:0;}

Magento: How to get actual price and special price of a product?

Loading Product
$_productId = 52;
$_product = Mage::getModel('catalog/product')->load($_productId);
Get Actual Price
// without currency sign
$_actualPrice = $_product->getPrice();
// with currency sign
$_formattedActualPrice = Mage::helper('core')->currency($_product->getPrice(),true,false);
Get Special Price
// without currency sign
$_specialPrice = $_product->getFinalPrice();
// with currency sign
$_formattedSpecialPrice =Mage::helper('core')->currency($_product->getFinalPrice(),true,false);

Magento Product Discount percent in Magento

Open app/design/frontend/yourpackage/yourtheme/template/catalog/product/price.phtml Find:
<?php endif; /* if ($_finalPrice == $_price): */ ?>
Add above it: place this custom code
<?php // Discount percents output start ?>
    <?php if($_finalPrice < $_price): ?>
    <?php $_savePercent = 100 - round(($_finalPrice / $_price)*100); ?>
        <p class="special-price yousave">
            <span class="label"><?php echo $this->__('You Save:') ?></span>
            <span class="price">
                <?php echo $_savePercent; ?>%
            </span>
        </p>
    <?php endif; ?>
<?php // Discount percent output end ?>

Magento Product Collection all filter codes

Load Product Collection
$collection = Mage::getModel('catalog/product')->getCollection();
or
$collection = Mage::getResourceModel('catalog/product_collection');
Add Attributes To Collection The product model is an enormous data set, and the more attributes we include in the load the longer it will take. By default, Magento will only load the basic data found in the ‘catalog_product_entity’ table (ID, SKU, Entity Type ID etc…) Add All Product Attributes
$collection->getAttributeToSelect('*');
Add Individual Product Attributes
$collection->addAttributeToSelect('name', 'description', 'brand');
Add Specific Price Attributes
$collection->addMinimalPrice();
$collection->addFinalPrice();
$collection->addTaxPercents();
Add Category IDs to Products
$collection->addCategoryIds();
Add Tier Pricing Info
$collection->addTierPriceData();
Add Product URL Rewrites
$collection->addUrlRewrite();
Filter Collection Being an EAV entity type means that we have access to the wonderful ‘addAttributeToFilter()’ method in addition to the standard ‘addFieldToFilter()’, which can take a larger range of arguments. The following are basic conditional filters, like you’d use in a MySQL query: Is Equal To
$collection->addAttributeToFilter('status', array('eq' => 1));
Is Not Equal To
$collection->addAttributeToFilter('visibility', array('neq' => 1));
Greater Than
$collection->addAttributeToFilter('price', array('gt' => 3));
Less Than
$collection->addAttributeToFilter('price', array('lt' => 3));
Greater Than or Equal To
$collection->addAttributeToFilter('price', array('gteq' => 4));
Less Than or Equal To
$collection->addAttributeToFilter('price', array('lteq' => 4));
Contains – with % wildcards
$collection->addAttributeToFilter('sku', array('like' => 'DVD%'));
Does Not Contain – with % wildcards
$collection->addAttributeToFilter('sku', array('nlike' => 'ABC%'));
Not In Array
$collection->addAttributeToFilter('entity_id', array('nin' => array(1,2,12)));
Is NULL
$collection->addAttributeToFilter('description', 'null');
Is Not NULL
$collection->addAttributeToFilter('description', 'notnull');
Further Filtering There are also more general filters that can be applied: Filter by Product IDs
$collection->addIdFilter(array(4,5,6));
Filter by Current Store
$collection->addStoreFilter();
Filter by Current Website
$collection->addWebsiteFilter();
Filter by Category
$collection->setStoreId($id)->addCategoryFilter($category);
Sort Collection Again, as with MySQL you can sort your collection by a chosen attribute in either ascending or descending order. Order by Attribute Ascending
$collection->setOrder('price', 'ASC');
Order by Attribute Descending
$collection->setOrder('name', 'DESC');
Random Order
$collection->setOrder('rand()');
Limit Collection If you’re in a situation where you want your product collection, but want to limit the number of results to a certain amount you can use the ‘setPageSize()’ method, and simply pass in your limit.
$collection->setPageSize(10);
$collection->getSelect()->limit(15);
Randomly Collection
$_productCollection->getSelect()->order(new Zend_Db_Expr('RAND()'));
Count Results Always useful when checking if any results have been returned.
$collection->count();
Return Only Product IDs Sometimes you’ll just need to get product IDs from your collection, rather than the rest of the product data. By Using ‘getAllIds’ you will receive a nice little array of product IDs for you to do with as you wish!
$collection->getAllIds();
Debug Collection Want to know why your collection keeps returning results? Using the ‘getSelect()’ method on your collection you can print the MySQL query that is getting sent to the database.
$collection->getSelect();

Magento Show Products in any page filter by category attribute

<h2>............................. Top Categories .............................</h2>
<?php
$categories = Mage::getModel('catalog/category')
              ->getCollection()
              ->addAttributeToSelect('*')
              ->addAttributeToFilter('top_category',1)
              ->addIsActiveFilter();
              foreach($categories as $_category)
              {
                     $_productCollection = Mage::getModel('catalog/product')
                     ->getCollection()
                     ->joinField('category_id', 'catalog/category_product', 'category_id', 'product_id = entity_id', null, 'left')
                     ->addAttributeToSelect('*')
                     ->addAttributeToFilter('category_id', $_category->getId())
                     ->addAttributeToSort('created_at', 'desc');
                     foreach($_productCollection as $_topproduct)
                     {
                       $modell = Mage::getModel('catalog/product');
                       $topproduct_id = $_topproduct->getId();
                       $_topproduct = $modell->load($topproduct_id);
                       $_img=Mage::getModel('catalog/product')->load($topproduct_id);
                            ?>
                     <div class="top-category-product">
                            <div class="top-category-product-name"><?php echo $_topproduct->getName(); ?></div>
                            <div class="top-category-product-image"><a href="<?php echo $_topproduct->getProductUrl() ?>"><img src="<?php echo Mage::helper('catalog/image')->init($_img, 'image')->resize(200,200); ?>"></a></div>
                     </div>
                            <?php
                     } 
              }             
?>


OR

<?php
  $categories = Mage::getModel('catalog/category')
              ->getCollection()
              ->addAttributeToSelect('*')
              ->addAttributeToFilter('top_category',1)
              ->addIsActiveFilter();
       foreach($categories as $_category)
       {
              $_productCollection = Mage::getResourceModel('catalog/product_collection')
                                   ->addAttributeToSelect('*')
                                   ->setOrder('created_at', 'DESC')
                                   ->addCategoryFilter($_category);
              foreach($_productCollection as $_topproduct)
                     {
                       $topproduct_id = $_topproduct->getId();
                       $modell = Mage::getModel('catalog/product');
                       $_topproduct = $modell->load($topproduct_id);
                       $_img=Mage::getModel('catalog/product')->load($topproduct_id);
                            ?>
                     <div class="top-category-product">
                            <div class="top-category-product-name"><?php echo $_topproduct->getName(); ?></div>
                            <div class="top-category-product-image"><a href="<?php echo $_topproduct->getProductUrl() ?>"><img src="<?php echo Mage::helper('catalog/image')->init($_img, 'image')->resize(200,200); ?>"></a></div>
                     </div>
                            <?php
                     } 
       }
?>

Or For Distinct Values

<?php
  $categories = Mage::getModel('catalog/category')
              ->getCollection()
              ->addAttributeToSelect('*')
              ->addAttributeToFilter('top_category',1)
              ->addIsActiveFilter();
       foreach($categories as $_category)
       {
              $_productCollection = Mage::getResourceModel('catalog/product_collection')
                                   ->addAttributeToSelect('*')
                                   ->setOrder('created_at', 'DESC')
                                   ->addCategoryFilter($_category);
              foreach($_productCollection as $_topproduct)
                     {
                       $topproduct_id[] = $_topproduct->getId();
                     } 
       }
       $TopProIdArr = array_unique($topproduct_id);
       foreach($TopProIdArr as $TopProId){
              $modell = Mage::getModel('catalog/product');
              $_topproduct = $modell->load($TopProId);
              $_img=Mage::getModel('catalog/product')->load($TopProId);?>
              <div class="top-category-product">
                     <div class="top-category-product-name"><?php echo $_topproduct->getName(); ?></div>
                     <div class="top-category-product-image"><a href="<?php echo $_topproduct->getProductUrl() ?>"><img src="<?php echo Mage::helper('catalog/image')->init($_img, 'image')->resize(200,200); ?>"></a></div>
              </div>
       
         <?php }?>

Magento Products collection in any page

<?php
$_productCollection = Mage::getModel('catalog/product')->getCollection();                              
$_productCollection->addAttributeToFilter('feature','1'); //custom attribute is yes/no(1,0)
$_productCollection->addAttributeToFilter('status', 1); //enabled
$_productCollection->addAttributeToFilter('visibility', 4); //catalog, search
?>
<?php  
foreach ($_productCollection as $_product)
{
       $model = Mage::getModel('catalog/product');
       $product_id = $_product->getId();
       $_product = $model->load($product_id);
       //echo $_product->getPrice()."<br>";
       //echo $_product->getName()."<br>";
       $_image=Mage::getModel('catalog/product')->load($product_id);
       //echo Mage::helper('catalog/image')->init($_image, 'image')."<br>";
       ?>
        <div class="feature-product">
            <div class="feature-product-price"><?php echo $_product->getPrice(); ?></div>
            <div class="feature-product-name"><?php echo $_product->getName(); ?></div>
            <div class="feature-product-image"><a href="<?php echo $_product->getProductUrl() ?>"><img src="<?php echo Mage::helper('catalog/image')->init($_image, 'image')->resize(200,200); ?>"></a></div>
        </div>
   <?php    
}                                       
?>