Friday 29 August 2014

How to get direction of scroll top or down in jquery

var previousScroll = 0;
$(window).scroll(function() {

 var currentScroll = $(this).scrollTop();
       if (currentScroll > previousScroll){
           $('#sc1_dwn').css('height',('+=15'));
       } else {
          $('#sc1_dwn').css('height',('-=15'));
       }
       previousScroll = currentScroll;
    
});

Wednesday 20 August 2014

how to get my cart total items in header in magento

<a href="<?php echo $this->getUrl('checkout/cart/') ?>"> Cart: <span>
<?php if(Mage::getSingleton('checkout/session')->getQuote()->getItemsSummaryQty() > 0)
{ ?>
<?php  echo  __(Mage::getSingleton('checkout/session')->getQuote()->getItemsSummaryQty()) ?>
<?php  } else { ?>
  0
<?php } ?>

show related products in product view page in magento

go to catalog.xml file and search below code

<reference name="content">
<block type="catalog/product_view" name="product.info" template="catalog/product/view.phtml">



insert related block after that block type:-

<block type="catalog/product_list_related" name="catalog.product.related" as="related" template="catalog/product/list/related.phtml"/>

</reference>

set this function in view.phtml file
<?php echo $this->getChildHtml('related'); ?>

set place holder value in form using javascript

 put below validation in text field as attribute.


onBlur="if(this.value == '') { this.value = 'Enter Your Name'; }" onFocus="if(this.value == 'Enter Your Name') { this.value = ''; }"

magento upgrade version 1.8.1- login issue

issue Onepage checkout: Already registered customer login redirects to create an account or login page when upgrade version 1.8.1

<input type="hidden" name="form_key" value="<?php  echo Mage::getSingleton('core/session')->getFormKey(); ?>" />

magento show product review on product view page

<?php
          $reviewData = Mage::getModel('review/review/summary'); 
          echo $nom_reviews = $reviewData->getTotalReviews($_product->getId());
?>

how to create layout of custom controller in magento

first create a controller suppose controller name is "test".
put this code here action name is "name".


<?php
class namespace_modulename_TestController extends Mage_Core_Controller_Front_Action{
public function nameAction()
{
    $this->loadLayout();  
   $this->renderLayout();
   
}
}
?>






after controller creation set layout go to design->template->layou open the xml file
put these code



<modulename_controllername_actionname> 
  <reference name="root">  
      <action method="setTemplate"><template>page/1column.phtml</template></action>  
    </reference>    
    <reference name="content">  
      <block type="core/template" name="getallcustomer_test" template="getallcustomer/test.phtml"/>  
    </reference>  
  </modulename_controllername_actionname>



and last send request for controller "modulname/controller/actionname".
print the all data of test.phtml file.

how to use ajax in magento module

first create a controller in controller folder of your module

and insert this script in phtml file where you want get result.

<script>
function loadXMLDoc(cid)
{
var xmlhttp;
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
   
  }
 
xmlhttp.open("GET","getallcustomer/ajax/index?a="+cid,true);
xmlhttp.send();
}
</script>
//"getallcustomer" :- is module name.
//"ajax":- is controller name (controller file name).
//"index":- is action of controller (function indexAction();)

<div id="myDiv">
ajax responce text print here.
</div>

how to get admin xml data value in magento

you put in this fuction 'section_code/group_code/field_code' and get xml value.

Mage::getStoreConfig('setting_all_customer/customer_group/status',Mage::app()->getStore());

how to remove index.php from base url by htaccess in magento

first you go to admin/system/configuration/web/seo select yes and save

second  this code insert in rootdirectory/.htaccess file

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

get all customers filter by top bestshaler and full order detail by customer in magento


first get all customer id and total sale:-

<?php $customer_ids=array();
$grand_total= array();
$orders = Mage::getModel('sales/order')->getCollection()
    ->addAttributeToSelect('customer_id')
    ->addAttributeToSelect('base_grand_total')
    ->addAttributeToSort('base_grand_total', 'DESC');
foreach ($orders as $order) {

    $ids=$order->getCustomerId();
    if(!empty($ids)){
    array_push($customer_ids,$ids);//push customer id in a array
   
    $gd_total+=$order->getBaseGrandTotal();
   
    array_push($grand_total,$gd_total);//push customer sale in a array
   
     }
   
}

sum total sale according to id

$result=array();
foreach($customer_ids as $k=>$key)
 {
   foreach($grand_total as $vk=>$val)
    {
      if($vk==$k)
       {
      if(!array_key_exists($key, $result))
       {
          $result[$key]=$val;
       }
       else{
        $sum_key=$result[$key];
        $result[$key]=($sum_key + $val);//sum same id value
       }

       }
    }

 }
 arsort($result);//sale value sorting sorting.


?>
$result array contain all id and total sale of customer.
get all detail of cutomer by id.
<table>
 <tr>
 <td width="50">ID</td> <td width="150">Name </td><td width="250">Email</td><td width="100">Total Purchase</td><td width="100">Detail</td></tr>
 <?php
 foreach($result as $ids =>$pur)
 {
 ?>
 <tr>

 <?php
$customer_data = Mage::getModel('customer/customer')->load($ids);
?>
<td><?php echo $customer_data['entity_id']; ?></td>
<td><?php echo $customer_data['firstname']." "; ?><?php echo $customer_data['lastname']; ?></td>
<td><?php echo $customer_data['email']; ?></td>
<td><?php echo $pur; ?></td>
 <td><a href="?id=<?php echo $customer_data['entity_id']; ?>">View</a></td>
 </tr>
 <?php
 }
?>
</table>

to get full detail of customer by customer id :-

<?php
$get_id=$_GET['id'];
 if(!empty($get_id))
{?>
<div id="detail" style="width:700px;background-color:#9933CC; margin-left:150px;">
<table style="margin-left:100px;">
 <tr>
 <td width="50">ID</td> <td width="150">Name </td><td width="250">Email</td></tr>
<tr>
 <?php //get full detail of customer by id
$customer_data = Mage::getModel('customer/customer')->load($get_id);
?>
<td ><?php echo $customer_data['entity_id']; ?></td>
<td><?php echo $customer_data['firstname']." "; ?><?php echo $customer_data['lastname']; ?></td>
<td><?php echo $customer_data['email']; ?></td>

</td>
 </tr>
 </table>
 </div>
 <div style="width:700px;background-color:#999933; margin-left:150px;">
 <table>
 <?php
  //get order id by customer id
 $orderCollection = Mage::getModel('sales/order')->getCollection()
 ->addFieldToFilter('customer_id',$get_id);
 foreach($orderCollection as $ord)
 {

 array_push($ord_id,$ord->getId());//push order id in a array
 }
// print_r($ord_id);
 ?>
 <tr>       
 <td width="150">Order NO.</td>
<td width="150">Product Id</td>
<td width="150">Product Sku</td>
<td width="150">Product Quantity</td>
<td width="150">Product Name</td>
<td width="150">Product Price</td>
<td width="150">Date</td>
</tr>
 <?php

  foreach($ord_id as $id_set){ 
 
 $orders = Mage::getModel("sales/order")->load($id_set);
   $ordered_items = $orders->getAllItems();
   foreach($ordered_items as $item){ 
        ?>
<tr>
<td ><?php echo $orders->getIncrementId(); ?></td>/*get order number*/       
<td ><?php echo $item->getItemId(); ?></td>
<td ><?php echo $item->getSku(); ?></td>
<td ><?php echo $item->getQtyOrdered(); ?></td>
<td ><?php echo $item->getName(); ?></td>
<td><?php echo $item->getPrice(); ?></td>
<td ><?php echo $item->getCreatedAt(); ?></td>
</tr>
<?php
         }
    }   
 ?>
 </table>
 </div>
</div>
<?php } ?>

cms page dynamically show on navigation bar order by in magento

//First you go to in database create new field "show_menu" in cms_page table. 
//After that  go in app/code/core/Mage/Adminhtml/Block/Cms/Page/Edit/Tab/main.php file and put thi code to add a fieled in admin page
 //First find this code
<?php

 $fieldset->addField('identifier', 'text', array(
            'name'      => 'identifier',
            'label'     => Mage::helper('cms')->__('URL Key'),
            'title'     => Mage::helper('cms')->__('URL Key'),
            'required'  => true,
            'class'     => 'validate-identifier',
            'note'      => Mage::helper('cms')->__('Relative to Website Base URL'),
            'disabled'  => $isElementDisabled
        ));
        ?>
//after these code paste below code
<?php

         $fieldset->addField('sort_order', 'text', array(
            'name'      => 'sort_order',
            'label'     => Mage::helper('cms')->__('Page Order'),
            'title'     => Mage::helper('cms')->__('Page Order'),
            'required'  => false,
        ));
       
        $fieldset->addField('show_menu', 'select', array(
          'label'     => Mage::helper('cms')->__('Show on top menu'),
            'title'     => Mage::helper('cms')->__('Show on top menu'),
            'name'      => 'show_menu',
            'required'  => true,
            'options'   => $model->getAvailableStatuses(),
            'disabled'  => $isElementDisabled,
        ));
       
?>

To  show on cms->page manage page insert these code in app/code/core/Mage/Adminhtml/Block/Cms/Page/Grid.php

<?php
//First find this code
  $this->addColumn('is_active', array(
            'header'    => Mage::helper('cms')->__('Status'),
            'index'     => 'is_active',
            'type'      => 'options',
            'options'   => Mage::getSingleton('cms/page')->getAvailableStatuses()
        ));
       
////after these code paste below code
         $this->addColumn('sort_order', array(
            'header'    => Mage::helper('cms')->__('Page Order'),
            'index'     => 'sort_order',
            'type'      => 'text',
        ));
       
        $this->addColumn('show_menu', array(
            'header'    => Mage::helper('cms')->__('Show on top menu'),
            'index'     => 'show_menu',
            'type'      => 'options',
            'options'   => Mage::getSingleton('cms/page')->getAvailableStatuses()
        ));
?>

and last you go to app/design/frontend/default/bestcase/template/page/html/topmenu.phtml

and put these code


<?php $cms_pages = Mage::getModel('cms/page')->getCollection()->addStoreFilter(Mage::app()->getStore()->getId());?>
<?php  $cms_pages->getSelect()->where('show_menu = 1')->order('sort_order ASC');

foreach($cms_pages as $_page)
{
$data = $_page->getData();
$pagestatus = $data['show_menu'];
if($pagestatus=="1"){
?>
<li><a href="<?php echo $this->getUrl($data['identifier']) ?>"><?php echo $data['title'];?> </a></li>

    <?php
    }
}
?>

 set up the page to show on top menu go to cms->page and add 1 in Show on top menu field click on save page.

add custom pagination on custom module in Magento

insert below code in blok file (app/code/local/Name_space/Yourmodule/Block/index.php)

<?php
protected function _prepareLayout()
    {
        parent::_prepareLayout();

        $pager = $this->getLayout()->createBlock('page/html_pager', 'custom.pager');
        $pager->setCollection($this->getCollection());
        $this->setChild('pager', $pager);
        $this->getCollection()->load();
       
        return $this;
    }

    public function getPagerHtml()
    {
        return $this->getChildHtml('pager');
    }
?>

//get pager in your page

<?php echo $this->getPagerHtml();?>

how to get current mode list or grid in magento

$this->getLayout()->createBlock('catalog/product_list_toolbar')->setChild('product_list_toolbar_pager', $pager)->getCurrentMode();

how to set toolbar on custom product collection in magento

<?php $toolbar = Mage::getBlockSingleton('catalog/product_list')->getToolbarBlock();
$toolbar->setCollection($collection);//insert collection of your  products
 echo $toolbar->toHtml(); ?>

javascript api for youtube video player controls

<script type="text/javascript" src="http://www.youtube.com/player_api"></script>
<script>
var player;
function onYouTubePlayerAPIReady() {
player2 = new YT.Player('player2');

}

function sto()
{
player2.pauseVideo();
player2.playVideo();
player2.stopVideo();
}
      
</script>
 <iframe width="350" height="315" id="player2" src="http://www.youtube.com/embed/T39hYJAwR40?enablejsapi=1" frameborder="0" allowfullscreen></iframe>

 <a href="javascript: void(0)" onclick="player2.playVideo(); return false">play</a>//in this function we can't set action.
| <a href="javascript: void(0)" onclick="player2.pauseVideo(); return false">pause</a>
| <a href="javascript: void(0)" onclick="player2.stopVideo(); return false">stop</a>

<a href="javascript:void(0);" onClick="sto();">close</a>//in this function we can set action according to requirement

how to display all products in one page in magento

<?php

$collection = Mage::getResourceModel('catalog/product_collection');
$collection->addAttributeToFilter('status',1);
$collection->addAttributeToSelect(array('name','id','url','small_image')); //get product field
$collection->addStoreFilter(); 
?>

how to get products by category id in magento

<?php
/*get all product by category*/

     foreach ($cat_id as $cat_ids)//for each run by category id
{
   
$catagory_model = Mage::getModel('catalog/category')->load($cat_ids);
$collection = Mage::getResourceModel('catalog/product_collection');
$collection->addCategoryFilter($catagory_model);
$collection->addAttributeToFilter('status',1);
$collection->addAttributeToSelect(array('name','id','url','small_image')); //get product field
$collection->addStoreFilter();         
if(!empty($collection))
{
foreach ($collection as $_product):?>

        <a href="<?php echo $_product->getProductUrl();?>"><img src="<?php echo Mage::helper('catalog/image')->init($_product, 'small_image')->resize(197, 167); ?>" />
        <span><?php echo $_product->getId();?></span><span><?php echo $_product->getName();?></span>  </a> 
<?php $pr_id= $_product->getId();?>

<?php array_push($pro_id, $pr_id ); ?>//push all product id in array.
 <?php   endforeach;

}else
    {
echo 'No products exists';

    }           
 ?> 

Parallax scrolling website with simple jquery

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>

<style type="text/css">
* {margin:0; padding: 0;}
    html, body {height:100%;}
    
      .bgParallax {
        font-family: 'Elsie', cursive;
        color:#FFF;
        margin: 0 auto;
        width: 100%;
        max-width: 1920px;
        position: relative;
        min-height: 100%;
        text-shadow:0 0 10px rgba(0,0,0,0.7);
    
        background-position: 50% 0;
        background-repeat: repeat;
        background-attachment: fixed;
      
    }
    
    /* Define backgrounds of divs */
    #aboutus {background-image: url(img.jpg);}
    #mission {
        background-image: url(img2.jpg);
        -webkit-box-shadow:-20px 0 20px 5px rgba(0,0,0,0.7);
        -moz-box-shadow:-20px 0 20px 5px rgba(0,0,0,0.7);
        -ms-box-shadow:-20px 0 20px 5px rgba(0,0,0,0.7);
        -o-box-shadow:-20px 0 20px 5px rgba(0,0,0,0.7);
        box-shadow:-20px 0 20px 5px rgba(0,0,0,0.7);
    }
  
    #name {background-image: url(img3.jpg);}
    #mis {
        background-image: url(img3.jpg);
        -webkit-box-shadow:-20px 0 20px 5px rgba(0,0,0,0.7);
        -moz-box-shadow:-20px 0 20px 5px rgba(0,0,0,0.7);
        -ms-box-shadow:-20px 0 20px 5px rgba(0,0,0,0.7);
        -o-box-shadow:-20px 0 20px 5px rgba(0,0,0,0.7);
        box-shadow:-20px 0 20px 5px rgba(0,0,0,0.7);
    }
  
    .bgParallax article {
      width: 70%;
      text-align: center;
      margin:0 auto;
      padding:20% 0 0;
    }
         article h1 {font-size:40px;}
    article p {line-height: 30px; font-size:20px; margin-top:15px;}
    article p a {color:#FFF; text-decoration:none; font-size:30px;}
#nav {
    list-style: none outside none;
    position: fixed;
    right: 20px;
    top: 100px;
    z-index: 99;
}
#nav li {
    margin: 0 0 5px;
}

#nav li.active a {
    background: none repeat scroll 0 0 #EC2028;
}
#nav li a {
    background: none repeat scroll 0 0 #FFFFFF;
    border-radius: 50px;
    display: block;
    font-size: 0;
    height: 15px;
    text-indent: -9999px;
    width: 15px;
}
a {
    color: #428BCA;
    text-decoration: none;
}
</style>
<script type="text/javascript">

$('div.bgParallax').each(function(){
    var $obj = $(this);

    $(window).scroll(function() {
        var yPos = -($(window).scrollTop() / $obj.data('speed'));

        var bgpos = '50% '+ yPos + 'px';

        $obj.css('background-position', bgpos );

    });
});

</script>
<script>
$(document).ready(function(){
$( '.searchbychar' ).on('click', function(event) {
    event.preventDefault();
    var target = "#" + $(this).data('target');
    //alert(target);
    $('html, body').animate({
        scrollTop: $(target).offset().top
    }, 2000);
});


});

$(window).scroll(function() {

    if ($(this).scrollTop() >= $('#aboutus').offset().top) {
       $('#nav #a1').addClass('active');
       $('#nav #a2 , #nav #a3 , #nav #a4').removeClass('active');
     }

    if ($(this).scrollTop() >= $('#mission').offset().top) {
      $('#nav #a1 , #nav #a3 , #nav #a4').removeClass('active');
      $('#nav #a2').addClass('active');

    }
     if ($(this).scrollTop() >= $('#name').offset().top) {
      $('#nav #a2 , #nav #a1 , #nav #a4').removeClass('active');
      $('#nav #a3').addClass('active');
    }
     if ($(this).scrollTop() >= $('#mis').offset().top) {
      $('#nav #a2 , #nav #a1 , #nav #a3').removeClass('active');
      $('#nav #a4').addClass('active');
    }
    });
</script>
<body>
    <ul id="nav">
        <li id="a1" class="active"><a class="searchbychar" href="#" data-target="aboutus" title="Next Section">first</a></li>
        <li id="a2"><a  class="searchbychar" href="#" data-target="mission" title="Next Section">second</a></li>
        <li id="a3"> <a  class="searchbychar" href="#" data-target="name" title="Next Section">third</a></li>
        <li id="a4"> <a  class="searchbychar" href="#" data-target="mis" title="Next Section">fourth</a></li>
          
    </ul>

    <div id="aboutus" class="bgParallax" data-speed="15">
      <article>
         <h1>Lorem Ipsum is simply dummy text of the printing and typesetting industry.</h1>
             <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text the 1500s,. </p>
         </article>
    </div>
    <div id="mission" class="bgParallax" data-speed="10">
         <article>
            <h1>Lorem Ipsum is simply dummy text of the printing and typesetting industry.</h1>
             <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text the 1500s,. </p>
         </article>

     </div>
  
    <div id="name" class="bgParallax" data-speed="15">
      <article>
         <h1>Lorem Ipsum is simply dummy text of the printing and typesetting industry.</h1>
             <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text the 1500s,. </p>
       

         </article>
    </div>
    <div id="mis" class="bgParallax" data-speed="10">
         <article>
             <h1>Lorem Ipsum is simply dummy text of the printing and typesetting industry.</h1>
             <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text the 1500s,. </p>
         </article>

    </div>



</body>
</html>

Tuesday 19 August 2014

Scroll to top and scroll to down of page in jquery

 <script>
    $(document).ready(function() {

    $('#gototop ').click(function(){
    $('html, body').animate({scrollTop:0}, 'slow');
    return false;
    });

   $('#gotobottom').click(function(){
    $('html, body').animate({scrollTop:$(document).height()}, 'slow');
    return false;
    });
    });
    </script>

Monday 18 August 2014

how to get all category and sub to sub category in a array in magento

<?php
/*get all category  */
$cat_id=array();
$pro_id=array();
$categories = Mage::getModel('catalog/category')->getCollection()
->addAttributeToSelect('id')
->addAttributeToSelect('is_active');

foreach ($categories as $category)
{
    if ($category->getIsActive()) {
        $entity_id = $category->getId();
        array_push($cat_id, $entity_id );//push all category id  in a array
    }
}
?>

how to get top level category and subcategory in magento

<?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() ?>
                </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>
                                <a href="<?php echo $_helper->getCategoryUrl($_subcategory) ?>">
                                    <?php echo $_subcategory->getName() ?>
                                     <?php echo $catId = $_subcategory->getId(); ?>
            <?php echo Mage::getModel('catalog/category')->load($catId)->getImageUrl();
                                    ?>
                                </a>
                            </li>
                        <?php endforeach; ?>
                    </ul>
                <?php endif; ?>
            </li>
        <?php endforeach; ?>
    </ul>
<?php endif; ?>

How to get top level category 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; ?>

How to get all images of a product in magento

$productId = 1; // product ID
$product = Mage::getModel('catalog/product')->load($productId); // load the product
$imageUrl = $product->getImageUrl(); // get image path
$imageThumbnailUrl = $product->getThumbnailUrl(); // get thumbnail path
And also  get product url

$product_url = $product->getProductUrl();

how to get all reviews and rating with products on frontend in magento


<?php

$con = Mage::getSingleton('core/resource')->getConnection('core_write');
$re=$con->query('SELECT rd.title, rd.detail, rd.nickname, rd.review_id, r.created_at, sum(vt.percent) as precn, r.entity_pk_value FROM review_detail AS rd LEFT JOIN review AS r USING  (review_id ) LEFT JOIN rating_option_vote AS vt USING ( review_id ) WHERE r.status_id = "1" GROUP BY vt.`review_id` order by r.created_at desc
limit 0, 5');

/*'SELECT rd.title, rd.detail, rd.nickname, r.created_at, sum(vt.percent) as precn, r.entity_pk_value FROM review_detail AS rd LEFT JOIN review AS r USING  (review_id ) LEFT JOIN rating_option_vote AS vt USING ( review_id ) WHERE r.status_id = "1" GROUP BY vt.`review_id`
';*/
?>

<div id="review_rates">
<table width="100%">
<tr class="main_review">
<td>
<?php while($rows=$re->fetch())
{
?>
<table class="tbl_repeate">
<tr>
<td rowspan="3">
<?php $productId = $rows['entity_pk_value'];
$product = Mage::getModel('catalog/product')->load($productId);
$imageThumbnailUrl = $product->getThumbnailUrl();
$product_url = $product->getProductUrl();

?>
<a href="<?php echo $product_url;?>"><img src="<?php echo $imageThumbnailUrl;?>"></a>
</td>
<td><h2><?php echo $rows['title']; ?></h2>
</td>
<tr>
<td>
<?php
$res_rate=$con->query("SELECT r.rating_code,rt.percent  FROM `rating` as r left join rating_option_vote as rt using(rating_id)  WHERE 
rt.review_id='".$rows['review_id']."' order by r.rating_code asc ");
 while($rows_rate=$res_rate->fetch())
{


?>
<table>
<tr>
<td>
<?php
echo $rows_rate['rating_code'];?>
</td>
<td>
<div class="ratings">
                    <div class="rating-box">
                <div style="width:<?php echo $rows_rate['percent'];  ?>%" class="rating"></div>
            </div>
        
       
    </div>
    </td>
    </tr>
    </table>
    <?php

}
?>
<table>
<tr>
<td>
Avrage
</td>
<td>
<div class="ratings">
                    <div class="rating-box">
                <div style="width:<?php echo (round($rows['precn']*100/300)); ?>%" class="rating"></div>
            </div>
                
    </div></td>
    </tr>
    </table>
    </td>
</tr>
<tr>
<td>
<strong><?php echo $rows['nickname']; ?></strong> Date <?php echo $rows['created_at']; ?></td>
</tr>
<tr>
<td colspan="2">
<?php echo $rows['detail']; ?>
</td>
</tr>
</table>

<?php

}


?>

</td>
   </tr>
   </table>
   </div>

How to call a PHTML file within a CMS page Magento

create a file like review.phtml
and save in catalog/product/review.phtml
create a cms page and insert following line in content field

{{block type="core/template" name="review" template="catalog/product/review.phtml"}}

How to add currency selector to magento header

 First go to below directory
/app/design/frontend/default/default/layout/page.xml

<block type="directory/currency" name="currency" template="directory/currency.phtml"/>

insert above  line in page.xml file in following header block it alredy exist

<block type="page/html_header" name="header" as="header">

</block>

How to check user login or not in magento

<?php $myStatus = Mage::getSingleton('customer/session')->isLoggedIn() ?>

<?php if($myStatus): ?>
 <a href="<?php echo $this->getUrl('shipping') ?>">Customer Support (24x7)</a>
<a href="<?php echo $this->getUrl('customer/account/logout/') ?>">Logout </a>

<?php else: ?>



<a href="<?php echo $this->getUrl('customer/account/login/') ?>">Login </a>|

<a href="<?php echo $this->getUrl('customer/account/create/') ?>">Register</a>

<?php endif ?>

How to site speed up through htaccess in magento

Enable Output Compression
This section will turn on the apache mod_deflate module, which compresses text, css, and javascript before it is sent to the browser. This results in a smaller download size. To enable, simply uncomment the appropriate lines so that it looks like the following:
<IfModule mod_deflate.c>

############################################
## enable apache served files compression
## http://developer.yahoo.com/performance/rules.html#gzip

    # Insert filter on all content
    SetOutputFilter DEFLATE
    # Insert filter on selected content types only
    AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css text/javascript application/javascript

    # Netscape 4.x has some problems...
    BrowserMatch ^Mozilla/4 gzip-only-text/html

    # Netscape 4.06-4.08 have some more problems
    BrowserMatch ^Mozilla/4\.0[678] no-gzip

    # MSIE masquerades as Netscape, but it is fine
    BrowserMatch \bMSIE !no-gzip !gzip-only-text/html

    # Don't compress images
    SetEnvIfNoCase Request_URI \.(?:gif|jpe?g|png)$ no-gzip dont-vary

    # Make sure proxies don't deliver the wrong content
    Header append Vary User-Agent env=!dont-vary

</IfModule>

Enable Expires Headers

    NOTE: This does not work on Litespeed servers.

Browsers use Expires headers to determine how long a page component can be cached. Static components, like images, should have far-future expires headers, but truthfully, all page components should have expires headers. To turn this feature on, just uncomment the appropriate line and add "ExpiresActive On" right above it. See below:

<IfModule mod_expires.c>

############################################
## Add default Expires header
## http://developer.yahoo.com/performance/rules.html#expires

    ExpiresActive On
    ExpiresDefault "access plus 1 year"

</IfModule>

Disable ETags
ETags are a way for browsers to validate cached components across subsequent visits. They can slow down a site served from a cluster if the cluster hasn't implemented them properly. It is best to just turn them off as follows:



############################################
## If running in cluster environment, uncomment this
## http://developer.yahoo.com/performance/rules.html#etags

    FileETag none

How to disable product which don't have image in magento

first comment these lines .

<?php /*?><?php if (($_products = $this->getProductCollection()) && $_products->getSize()): ?>
<?php $_columnCount = $this->getColumnCount(); ?><?php */?>

and replce this code :-

<?php $_products = Mage::getModel('catalog/product')
->getCollection()
->addAttributeToSelect('*')
->addAttributeToFilter('small_image',array('neq'=>'no_selection'));
?>

How to get product base image in magento

<?php $_gallery = Mage::getModel('catalog/product')->load($_product->getId())->getMediaGalleryImages();  ?>
           <?php if (count($_gallery) > 0): ?>
          
                    <?php foreach ($_gallery as $_image ):  ?>
                    <?php if($this->htmlEscape($_image->getLabel())=="hover"):
                   
              ?>
                            <a href="<?php echo $_product->getProductUrl() ?>"   title="<?php echo $this->htmlEscape($_product->getName()) ?>" onmouseout="imgout(this);" style="display:none;" id="hover_<?php echo $i;?>">    <img src="<?php echo $this->helper('catalog/image')->init($this->getProduct(), 'image', $_image->getFile())->resize(135, 135); ?>" width="135" height="135"  alt="<?php echo $this->htmlEscape($_image->getLabel()) ?>" title="<?php echo $this->htmlEscape($_image->getLabel()) ?>"   /></a>
                      <?php endif; ?>
                     
                     <?php endforeach;  ?>
                  
                <?php endif; ?>   
</div>

How to change image on mouseover in prduct list in magento


 Paste below script on product list page.

<script>
function imgover(obj) {
var id1 = obj.id;

    document.getElementById(id1).style.display = 'none';
    document.getElementById('hover_' + id1).style.display = 'block';
 
}

function imgout(h_obj) {
var id1 = h_obj.id;
var myarr = id1.split("_");

      document.getElementById(myarr[1]).style.display = 'block';
      document.getElementById(id1).style.display = 'none';
}
</script>

<div class="pro-img">   

<a href="<?php echo $_product->getProductUrl() ?>" id="<?php echo $i;?>" onmouseover="imgover(this);"  title="<?php echo $this->htmlEscape($_product->getName()) ?>">
<img src="<?php echo $this->helper('catalog/image')->init($_product, 'small_image')->resize(135) ?>" width="135" height="135"  alt="<?php echo $this->htmlEscape($_product->getName()) ?>"  /></a>//default---image---of----prduct.

How to call new products in static block in magento

{{block type="catalog/product_new" name="home.catalog.product.new" alias="product_homepage" template="catalog/product/new.phtml"}}

How to call layered navigation in cms block in magento

{{block type="catalog/layer_view" name="catalog.leftnav" before="-" template="catalog/layer/view.phtml"}}

How to call contact form in cms block in magento

{{block type="core/template" name="contactForm" form_action="/contacts/index/post" template="contacts/form.phtml"}}

Skin url in magento

<?php  echo $this->getSkinUrl();  ?>

How to call newsletter in phtml file in magento

<?php echo $this->getLayout()->createBlock('newsletter/subscribe')->setTemplate('newsletter/subscribe.phtml')->toHtml(); ?>

How to run delete query in magento

$con = Mage::getSingleton('core/resource')->getConnection('core_write');

$condition = array($con->quoteInto('id=?', "$actid"));
$con->delete('wolesaler_table', $condition);

How run insert query in magento

<?php
$connection = Mage::getSingleton('core/resource')->getConnection('core_write');
    $connection->beginTransaction();
    $fields = array();
    $fields['cname']= "$com_name";
   $fields['name']= "$name";
   $fields['email']= "$email";
   $fields['phone']= "$phone";
   $fields['account']= "$account";
    $fields['customer_id']= "$custm_id";
   $fields['date']= NOW();
    $connection->insert('wolesaler_table', $fields);
    $connection->commit();
?>

How to set db connection in magento

<?php
$con = Mage::getSingleton('core/resource')->getConnection('core_write');

/*------------------------------------ select query*/
$re=$con->query('select * from teble_name');
while($rows=$re->fetch())
{
$rows['field_name'];
}
?>

How to call cms block in phtml file in magento

<?php echo $this->getLayout()->createBlock('cms/block')->setBlockId('block_name')->toHtml();?>

How does ssl work ?

A . TLS and its predecessor SSL make significant use of certificate authorities. Once your browser requests a secure page and adds the "s" onto "http," the browser sends out the public key and the certificate, checking three things: 1) that the certificate comes from a trusted party; 2) that the certificate is currently valid; and 3) that the certificate has a relationship with the site from which it's coming.

The browser then uses the public key to encrypt a randomly selected symmetric key. Public-key encryption takes a lot of computing, so most systems use a combination of public-key and symmetric key encryption. When two computers initiate a secure session, one computer creates a symmetric key and sends it to the other computer using public-key encryption. The two computers can then communicate using symmetric-key encryption. Once the session is finished, each computer discards the symmetric key used for that session. Any additional sessions require that a new symmetric key be created, and the process is repeated.

B.
    1.Browser connects to a web server (website) secured with SSL (https). Browser requests that the server identify itself.
    2.Server sends a copy of its SSL Certificate, including the server’s public key.
    3.Browser checks the certificate root against a list of trusted CAs and that the certificate is unexpired, unrevoked, and that its common name is valid for the website that it is connecting to. If the browser trusts the certificate, it creates, encrypts, and sends back a symmetric session key using the server’s public key.
    4.Server decrypts the symmetric session key using its private key and sends back an acknowledgement encrypted with the session key to start the encrypted session.
    5. Server and Browser now encrypt all transmitted data with the session key.

What Is SSL?

SSL (Secure Sockets Layer) is a standard security technology for establishing an encrypted link between a server and a client—typically a web server (website) and a browser; or a mail server and a mail client (e.g., Outlook).

SSL allows sensitive information such as credit card numbers, social security numbers, and login credentials to be transmitted securely. Normally, data sent between browsers and web servers is sent in plain text—leaving you vulnerable to eavesdropping. If an attacker is able to intercept all data being sent between a browser and a web server they can see and use that information.

More specifically, SSL is a security protocol. Protocols describe how algorithms should be used; in this case, the SSL protocol determines variables of the encryption for both the link and the data being transmitted.

How to create xml for google rss feed in magento

 Create a php file in root directory and paste these code.After these code will run then a xml file will be create in root directory.


<?php
define('MAGENTO', realpath(dirname(__FILE__)));
    require_once MAGENTO . '/app/Mage.php';
    Mage::app();
    //$storename='default';
    //$file = "products_xml.xml";
    //if (file_exists($file)) { unlink ($file); }
?>


<?php

$products = Mage::getModel('catalog/product')
            ->getCollection()
            ->addAttributeToSelect('entity_id')
            ->addAttributeToSelect('sku')
            ->addAttributeToSelect('name')
            ->addAttributeToSelect('description')
            ->addAttributeToSelect('short_description')
->addAttributeToSelect('url_key')
            ->addAttributeToSelect('image')
            ->addAttributeToSelect('manufacturer')
            ->addAttributeToSelect('price')
            ->addAttributeToSelect('product_type')
            ->addAttributeToSelect('weight')
            ->addAttributeToSelect('quantity')
            ->addAttributeToSelect('availability')
->addAttributeToSelect('condition')
->addAttributeToSelect('shipping')
->addAttributeToSelect('tax')
            ->addAttributeToSelect('is_in_stock')
            ->addAttributeToFilter('status', array('eq' => '1'))
            ->addAttributeToFilter('type_id', array('eq' => 'simple'))
            ->addAttributeToFilter('visibility', 4);

$xml='';
//prep output
    $tab = "\t";
    $br = "\n";
    $xml = '<?xml version="1.0" encoding="UTF-8" ?>'.$br;
    $xml .= '<rss version ="2.0" xmlns:g="http://base.google.com/ns/1.0">'.$br;
    $xml .= '<channel>'.$br;
    $xml .= '<title>https://xpartws.com/</title>'.$br;
    $xml .= '<description>Xpartws wholesale corp the personal service you can afford</description>'.$br;
    $xml .= '<link>https://xpartws.com/</link>'.$br;
   
// while loop, this will cycle through the products and echo out all the variables
foreach($products as $_product){
// collect all variables
$total_qty = (int) Mage::getModel('cataloginventory/stock_item')->loadByProduct($_product)->getQty();
if($total_qty != '0' && $_product->isSaleable()){
$sku         = $_product->getSku();
$name         = $_product->getName();
$description = trim($_product->getData('short_description'));


$url         = 'https://xpartws.com/index.php/'.trim($_product->getData('url_key')).'.html';

$img         ='http://xpartws.com/media/catalog/product'.trim($_product->getData('image'));
$condition     = $r['productCondition'];
$price         = number_format(trim($_product->getPrice()),2);
$weight      = trim($_product->getWeight());
/*
require("../includes/config.php"); */

$xml.= '<item>'.$br;
$xml.='<title>'.str_replace('&','&amp;',$_product->getName()).'</title>'.$br;
                     $xml.='<link>'.$url.'</link>'.$br;
                     $xml.='<category>Electronics &gt; Communications &gt; Telephony &gt; Mobile Phones &gt; Smartphones</category>'.$br;
                   
        $xml.='<description>'.str_replace('&','&amp;',strip_tags($description)).'</description>'.$br;
        $xml.='<g:id>'.$sku.'</g:id>'.$br;
        $xml.='<g:condition>New</g:condition>'.$br;
        $xml.='<g:price>'.$price.'</g:price>'.$br;
        $xml.='<g:availability>in stock</g:availability>'.$br;
        $xml.='<g:image_link>'.$img.'</g:image_link>'.$br;
        /*$xml.= '<g:shipping>shipping</g:shipping>'.$br;
        $xml.='<g:gtin>88089927874267</g:gtin>'.$br;*/
        $xml.='<g:brand>'.trim($_product->getAttributeText('manufacturer')).'</g:brand>'.$br;
        /*$xml.= '<g:isbn>'.$sku.'</g:isbn>'.$br;*/
        $xml.= '<g:mpn>'.$sku.'</g:mpn>'.$br;
        $xml.= '<g:product_type>'.trim($_product->getTypeId()).'</g:product_type>'.$br;
        $xml.= '<g:shipping_weight>'.trim($_product->getWeight()).' lb</g:shipping_weight>'.$br;
        $xml.= '<g:google_product_category>Electronics &gt; Communications &gt; Telephony &gt; Mobile Phones &gt; Smartphones</g:google_product_category>'.$br;

$xml.='</item>'.$br;
}

}


/*$xml.= '<item>'.$br;
$xml.='<title>'.$name.'</title>'.$br;
                     $xml.='<link>'.$url.'</link>'.$br;
        $xml.='<description>'.$description.'</description>'.$br;
        $xml.='<g:id>'.$sku.'</g:id>'.$br;
        $xml.='<g:condition>New</g:condition>'.$br;
        $xml.='<g:price>'.$price.'</g:price>'.$br;
        $xml.='<g:availability>in stock</g:availability>'.$br;
        $xml.='<g:image_link>'.$img.'</g:image_link>'.$br;
        $xml.= '<g:shipping>'.$br;
        $xml.= '<g:country>US</g:country>'.$br;
        $xml.='<g:service>Standard</g:service>'.$br;
        $xml.='<g:price>14.95 USD</g:price>'.$br;
        $xml.='</g:shipping>'.$br;
        $xml.='<g:gtin>8808992787426</g:gtin>'.$br;
        $xml.='<g:brand>'.trim($_product->getBrand().'</g:brand>'.$br;
        $xml.= '<g:mpn>M2262D-PC</g:mpn>'.$br;
        $xml.= '<g:product_type>Consumer Electronics &gt; TVs &gt; Flat Panel TVs</g:product_type>'.$br;

$xml.='</item>'.$br;*/


$xml.= '</channel>'.$br;
        $xml.= '</rss>'.$br;
               
   
    $handle = fopen('google_feeds.xml','w+');
    fwrite($handle,$xml);
    fclose($handle);


echo "<h2 style=color:green;>Your product data Successfully exported in".' '.'slw-'.date('y-m-d').'-'.time().'.xml'."</h2>";

?>
<strong>Download from here</strong><br />
<a href="https://xpartws.com/google_feeds.xml"><?php echo 'https://xpartws.com/google_feeds.xml'; ?></a><br /><br />


How to set count down in jquery

<script type="text/javascript">

function cdtime(container, targetdate){
if (!document.getElementById || !document.getElementById(container)) return
this.container=document.getElementById(container)
this.currentTime=new Date()
this.targetdate=new Date(targetdate)
this.timesup=false
this.updateTime()
}

cdtime.prototype.updateTime=function(){
var thisobj=this
this.currentTime.setSeconds(this.currentTime.getSeconds()+1)
setTimeout(function(){thisobj.updateTime()}, 1000) //update time every second
}

cdtime.prototype.displaycountdown=function(baseunit, functionref){
this.baseunit=baseunit
this.formatresults=functionref
this.showresults()
}

cdtime.prototype.showresults=function(){
var thisobj=this


var timediff=(this.targetdate-this.currentTime)/1000 //difference btw target date and current date, in seconds
if (timediff<0){ //if time is up
this.timesup=true
this.container.innerHTML=this.formatresults()
return
}
var oneMinute=60 //minute unit in seconds
var oneHour=60*60 //hour unit in seconds
var oneDay=60*60*24 //day unit in seconds
var dayfield=Math.floor(timediff/oneDay)
var hourfield=Math.floor((timediff-dayfield*oneDay)/oneHour)
var minutefield=Math.floor((timediff-dayfield*oneDay-hourfield*oneHour)/oneMinute)
var secondfield=Math.floor((timediff-dayfield*oneDay-hourfield*oneHour-minutefield*oneMinute))
if (this.baseunit=="hours"){ //if base unit is hours, set "hourfield" to be topmost level
hourfield=dayfield*24+hourfield
dayfield="n/a"
}
else if (this.baseunit=="minutes"){ //if base unit is minutes, set "minutefield" to be topmost level
minutefield=dayfield*24*60+hourfield*60+minutefield
dayfield=hourfield="n/a"
}
else if (this.baseunit=="seconds"){ //if base unit is seconds, set "secondfield" to be topmost level
var secondfield=timediff
dayfield=hourfield=minutefield="n/a"
}
this.container.innerHTML=this.formatresults(dayfield, hourfield, minutefield, secondfield)
setTimeout(function(){thisobj.showresults()}, 1000) //update results every second
}



function formatresults(){
if (this.timesup==false){//if target date/time not yet met
var displaystring=arguments[0]+" days "+arguments[1]+" hours "+arguments[2]+" minutes "+arguments[3]+" seconds left until March 23, 2009 18:25:00"
}
else{ //else if target date/time met
var displaystring="Future date is here!"
}
return displaystring
}

function formatresults2(){
if (this.timesup==false){ //if target date/time not yet met
var displaystring="<ul><li>"+arguments[0]+" <span>days</span></li><li> "+arguments[1]+" <span>hours</span></li><li> "+arguments[2]+" <span>minutes</span></li><li> "+arguments[3]+" <span>seconds</span></li></ul>"
}
else{ //else if target date/time met
var displaystring="" //Don't display any text
alert("Christmas is here!") //Instead, perform a custom alert
}
return displaystring
}

</script>


<div id="countdowncontainer"></div>
<br />
<div id="countdowncontainer2"></div>

<script type="text/javascript">
//var future_date = "January 25, 2014 15:10:25";
//var future_date = "February 25, 2014 15:10:25";
//var future_date = "March 25, 2014 15:10:25";
//var future_date = "April 25, 2014 15:10:25";
//var future_date = "May 25, 2014 15:10:25";
//var future_date = "June 25, 2014 15:10:25";
//var future_date = "July 25, 2014 15:10:25";
//var future_date = "August 25, 2014 15:10:25";
//var future_date = "September 25, 2014 15:10:25";
var future_date = "October 25, 2014 15:10:25";
//var future_date = "November 25, 2014 15:10:25";
//var future_date = "December 22, 2014 15:10:25";

/*var futuredate=new cdtime("countdowncontainer", "June 28, 2009 18:25:00")
futuredate.displaycountdown("days", formatresults)*/

var currentyear=new Date().getFullYear()
//dynamically get this Christmas' year value. If Christmas already passed, then year=current year+1
var thischristmasyear=(new Date().getMonth()>=11 && new Date().getDate()>25)? currentyear+1 : currentyear
var christmas=new cdtime("caon-down", future_date)
christmas.displaycountdown("days", formatresults2)
</script>

Add active class on click using javascript

<script>
function act()
{
var selector, elems, makeActive;

selector = '.nav li';

elems = document.querySelectorAll(selector);

makeActive = function () {
    for (var i = 0; i < elems.length; i++)
        elems[i].classList.remove('active');

    this.classList.add('active');
};

for (var i = 0; i < elems.length; i++)
    elems[i].addEventListener('mousedown', makeActive);
}
</script>

<ul class="nav">
        <li onclick="act();"><a href="#intro" title="Next Section">a</a></li>
        <li onclick="act();"><a href="#second" title="Next Section">b</a></li>
        <li onclick="act();"><a href="#third" title="Next Section">c</a></li>
       <!-- <li><a href="#fifth" title="Next Section"><img src="slid/images/dot.png" alt="Link" /></a></li> -->
   
    </ul>

Add active class on scrolling using jQuery

$(window).scroll(function() {

    if ($(this).scrollTop() >= $('#intro').offset().top) {
       $('#nav #a1').addClass('active');
       $('#nav #a2').removeClass('active');
       $('#nav #a3').removeClass('active');
    }

    if ($(this).scrollTop() >= $('#second').offset().top) {
      $('#nav #a1').removeClass('active');
      $('#nav #a2').addClass('active');
      $('#nav #a3').removeClass('active');
    }
     if ($(this).scrollTop() >= $('#third').offset().top) {
      $('#nav #a2').removeClass('active');
      $('#nav #a3').addClass('active');
    }