Product level shipping in Magento

By default Magento don’t let you set shipping cost per product level. You can do it by using some technique with flatrate shipping method.

Step 1: Create attribute.
Create a attribute from admin panel catalog->attributes, lets give it a name shipping_world and add this attribute to your default “attribute set” to do that go to catalog -> “attribute set” click your default attribute set then drag shipping_world attribute and drop in attribute tree in left.

Step 2: Edit Flatrate Module.
overwrite/extend the flatrate carrier model of magento or just open file app/code/core/Mage/Shipping/Model/Carrier/Flatrate.php

class Mage_Shipping_Model_Carrier_Flatrate
    extends Mage_Shipping_Model_Carrier_Abstract
    implements Mage_Shipping_Model_Carrier_Interface
{

    protected $_code = 'flatrate';
    protected $_isFixed = true;

    /**
     * Enter description here...
     *
     * @param Mage_Shipping_Model_Rate_Request $data
     * @return Mage_Shipping_Model_Rate_Result
     */
    public function collectRates(Mage_Shipping_Model_Rate_Request $request)
    {
        if (!$this->getConfigFlag('active')) {
            return false;
        }

        $freeBoxes = 0;
        if ($request->getAllItems()) {
            foreach ($request->getAllItems() as $item) {

                if ($item->getProduct()->isVirtual() || $item->getParentItem()) {
                    continue;
                }

                if ($item->getHasChildren() && $item->isShipSeparately()) {
                    foreach ($item->getChildren() as $child) {
                        if ($child->getFreeShipping() && !$child->getProduct()->isVirtual()) {
                            $freeBoxes += $item->getQty() * $child->getQty();
                        }
                    }
                } elseif ($item->getFreeShipping()) {
                    $freeBoxes += $item->getQty();
                }
            }
        }
        $this->setFreeBoxes($freeBoxes);

        $result = Mage::getModel('shipping/rate_result');
        if ($this->getConfigData('type') == 'O') { // per order
            $shippingPrice = $this->getConfigData('price');
        } elseif ($this->getConfigData('type') == 'I') { // per item
            $shippingPrice = ($request->getPackageQty() * $this->getConfigData('price')) - ($this->getFreeBoxes() * $this->getConfigData('price'));
        } else {
            $shippingPrice = false;
        }
		
        $shippingPrice = $this->getFinalPriceWithHandlingFee($shippingPrice);
		$shippingPrice = $this->get_pro_ship();

        if ($shippingPrice !== false) {
            $method = Mage::getModel('shipping/rate_result_method');

            $method->setCarrier('flatrate');
            $method->setCarrierTitle($this->getConfigData('title'));

            $method->setMethod('flatrate');
            $method->setMethodTitle($this->getConfigData('name'));

            if ($request->getFreeShipping() === true || $request->getPackageQty() == $this->getFreeBoxes()) {
                $shippingPrice = '0.00';
            }


            $method->setPrice($shippingPrice);
            $method->setCost($shippingPrice);

            $result->append($method);
        }

        return $result;
    }

    public function getAllowedMethods()
    {
        return array('flatrate'=>$this->getConfigData('name'));
    }
	
	public function get_pro_ship()
	{
	Mage::getSingleton('core/session', array('name'=>'frontend'));
	$session = Mage::getSingleton('checkout/session');
	$cart_items = $session->getQuote()->getAllItems();
	$_helper = Mage::helper('catalog/output');
 	$custom_ship=0;
	foreach( $cart_items as $items ){
   	
		$cur_fproduct = Mage::getModel('catalog/product')->load($items->getProduct_id());
	$custom_ship +=($items->getQty())*($_helper->productAttribute($cur_fproduct, $cur_fproduct->getShippingWorld(), 'shipping_world'));						
	}
		
		
	return $custom_ship ;	
		
	}// function end

}

The value given in shipping_world attribute of product will be the flat shipping rate of that product.
That’s it. Clear cache and add/edit product where you can input shipping_world value in for each product. value must be numeric without space. then that value will be the shipping flate rate of products. checkingout with multiple product will add all shipping costs per item basis.

Easy Multiple Copy to Clipboard by ZeroClipboard

It almost stuck my head today when fixing this multiple zeroclipboard button by ZeroClipboard library.

<script type="text/javascript" src="ZeroClipboard.js"></script>
<script language="JavaScript">
////copy to clip
  	var clip = null;

   function $(id) { return document.getElementById(id); }

   function init() 
   {
      clip = new ZeroClipboard.Client();
      clip.setHandCursor( true );
   }

   function move_swf(ee)
   {    
      copything = document.getElementById(ee.id+"_text").value;
      clip.setText(copything);

         if (clip.div)
		 {	  
            clip.receiveEvent('mouseout', null);
            clip.reposition(ee.id);
         }
         else{ clip.glue(ee.id);   }
 
         clip.receiveEvent('mouseover', null);
 
   }    
   
</script>

<body onload="init();">
<table width="0" border="0">
  <tr>
    <td><input type='text' id='textid_text' value='your text' /></td>
    <td><div id='textid' onMouseOver='move_swf(this)' class='clip_button'>COPY</div></td>
  </tr>
  <tr>
    <td><input type='text' id='textid2_text' value='your text 2' /></td>
    <td><div id='textid2' onMouseOver='move_swf(this)' class='clip_button'>COPY</div></td>
  </tr>
  <tr>
    <td><input type='text' id='textid3_text' value='your text 3' /></td>
    <td><div id='textid3' onMouseOver='move_swf(this)' class='clip_button'>COPY</div></td>
  </tr>
  <tr>
    <td><input type='text' id='textid4_text' value='your text 4' /></td>
    <td><div id='textid4' onMouseOver='move_swf(this)' class='clip_button'>COPY</div></td>
  </tr>
  <tr>
    <td><input type='text' id='textid5_text' value='your text 5' /></td>
    <td><div id='textid5' onMouseOver='move_swf(this)' class='clip_button'>COPY</div></td>
  </tr>
</table>
</body>

You can generate above html dynamically by loop and generate ids with unique values.
See Demo

Download

Show Top Selling Products in Magento

This a simple best seller product viewing code. you can put it in template. this will grab all the sold product according to sold amount, you can simply put a loop break to show number of products you want to show .

<?php /* Best Seller*/
 
$visibility = array(
Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH,
Mage_Catalog_Model_Product_Visibility::VISIBILITY_IN_CATALOG
                     );
$storeId = Mage::app()->getStore()->getId();
$_productCollection = Mage::getResourceModel('reports/product_collection')
                            ->addAttributeToSelect('*')
           ->addOrderedQty()
                             ->addAttributeToFilter('visibility', $visibility)
                            ->setOrder('ordered_qty', 'desc');
 
           //print_r($_productCollection);
           foreach($_productCollection as $bs_product){
           echo '<li><a href="'.$bs_product->getUrl_path().'">'.$bs_product->Name.'</a></li>';
              }
?>

Category with Product in Menu Navigation of Magento frontend

Shops with a few products can view their product according to category in navigation. It will simplify a for customer to find their product find easily.
There is no such feature in magento default layered navigation. So, I created one, It take me 7 hr to write few line of code :-( you can add this code in cms page, /app/design/frontend/base/default/template/page/2column-right.phtml or any where in your theme. have fun !

<ul><?php
$collection = Mage::getModel('catalog/category')->getCollection();
$collection->addAttributeToSelect('url_key')
->addAttributeToSelect('id')
->load();
foreach ($collection AS $_cat)
{
if(($_cat->getId()!=1) && ($_cat->getId()!=2))
{
$cat = Mage::getModel('catalog/category')->load($_cat->getId());
echo '<li>'.$cat->getName().' </li>';
$cur_category = Mage::getModel('catalog/category')->load($_cat->getId());
$_productCollection =Mage::getResourceModel('catalog/product_collection')
->addCategoryFilter($cur_category)
->setOrder('position', 'ASC');
echo '<ul>';
foreach ($_productCollection AS $_product)
{
$cur_product = Mage::getModel('catalog/product')->load($_product->getId());
echo '<li><a href="'.$cur_product->getUrl_key().'.html">'.$cur_product->getName().'</a></li>';
}
echo '</ul></dd>';
}
} //end menu
?></ul>

Create Joomla registered user by component

Creating a Joomla component that create user, can help you to add user from other forum, script etc… or from a simple mailing list. below function will help you to create a registered user from email address and name. pass the array with your user data.

$qcnewu=array(
'name'=>$gname,
'username'=>$gemail,
'email'=>$gemail,
'password'=>$tmp_pwd,
'password2'=>$tmp_pwd,
'id'=>"0",
'gid'=>"0"
);
 
function auto_usr($qcnewu)
   {
      $db =& JFactory::getDBO();
 
      global $mainframe;
      $user       = clone(JFactory::getUser());
      $pathway    =& $mainframe->getPathway();
      $config     =& JFactory::getConfig();
      $authorize  =& JFactory::getACL();
      $document   =& JFactory::getDocument();
      $newUsertype = 'Registered';
 
      if (!$user->bind( $qcnewu, 'usertype' )) {
         JError::raiseError( 500, $user->getError());
      }
 
      $user->set('id', 0);
      $user->set('usertype', $newUsertype);
      $user->set('gid', 18);
      $user->set('lastvisitDate', '0000-00-00 00:00:00');
      $user->set('sendEmail', 0);
      $date =& JFactory::getDate();
      $user->set('registerDate', $date->toMySQL());
 
      jimport('joomla.user.helper');
      //$user->set('activation', JUtility::getHash( JUserHelper::genRandomPassword()) );
      $user->set('block', '0');
 
      // Show error with registration
      if ( !$user->save() )
      {
         //JError::raiseWarning('', JText::_( $user->getError()));
         return false;
      }else return true;
 
   }