Sunday, May 8

How to Track Visitor´s Information in Magento

now we will see how to track the visitors information in magento. visitors in formations means we can track visitors ip address,browser, visit time and visitor id, etc.

The following scriptfetches the vistor data

$visitorData = Mage::getSingleton('core/session')->getVisitorData();
 
// printing visitor information data
echo "
"; print_r($visitorData); echo "
";

now we will get an array of visitor information data

Array
(
[] =>
[server_addr] => 154784124
[remote_addr] => 258974125
[http_secure] =>
[http_host] => 127.0.0.1
[http_user_agent] => Mozilla/4.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/534.10 (KHTML, like Gecko) Chrome/8.0.552.237 Safari/534.10
[http_accept_language] => en-US,en;q=0.8
[http_accept_charset] => ISO-8859-1,utf-8;q=0.7,*;q=0.3
[request_uri] => /magentotalks/index.php/contacts/
[session_id] => 13qm5u80238vb15lupqcac97r5
[http_referer] => http://127.0.0.1/magentotalks/
[first_visit_at] => 2011-06-14 10:12:03
[is_new_visitor] =>
[last_visit_at] => 2011-06-17 11:54:18
[visitor_id] => 51
[last_url_id] => 149
)

In the above array, the server_addr and remote_addr are in different form than usual. The (IPv4) Internet Protocol dotted address has been converted into a proper address using ip2long PHP function. You can get the same kind of value from the following code:-

// user's ip address (visitor's ip address)
$remoteAddr = Mage::helper('core/http')->getRemoteAddr(true);
 
// server's ip address (where the current script is)
$serverAddr = Mage::helper('core/http')->getServerAddr(true);
 
Ref : http://blog.chapagain.com.np/magento-track-visitors-information/ 

Saturday, May 7

How to create a custom module in magento

Here is the steps to create the module in Magento

Step: 1

Inform Magento that you have a custom module.
app/etc/modules/Fido_All.xml Notice the _All in the xml file name. I can declare all of my modules here.
<?xml version="1.0"?>
<config>
<modules>
<fido_example>
<active>true</active>
<codepool>local</codePool>
</Fido_Example>
</modules>
</config>

Step: 2

Need to create directories as necessary.
app/code/local/Fido/Example/etc/config.xml

<?xml version="1.0"?>
<config>
<modules>
<fido_example>
<version>0.1.0</version>
</Fido_Example>
</modules>
<global>
<blocks>
<fido_example>
<class>Fido_Example_Block</class>
</fido_example>
</blocks>
</global>
</config>

I have informed Magento of my module version (it’s an arbitrary version). Version matters when you set up your module to be update-able. (A newer version will inform Magento to run the update files if you have them).
I have also informed Magento that my module contains block files which are found in fido/example/block. My class name will have “Fido_Example_Block”. If you want to see the many possibilities of stuff that goes in here, check out Mage config files (such as Catalog/etc/config.xml). You’ll also see other xml files in there. Those explanations are for another post.

Step: 3

Here is my block code. It doesn’t really do anything, but shows some functionality.
app\code\local\Fido\Example\Block\View.php

<?php
/**
* Example View block
*
* @codepool   Local
* @category   Fido
* @package    Fido_Example
* @module     Example
*/
class Fido_Example_Block_View extends Mage_Core_Block_Template
{
private $message;
private $att;

 
protected function createMessage($msg) {
$this->message = $msg;
}

 
public function receiveMessage() {
if($this->message != '') {
return $this->message;
} else {
$this->createMessage('Hello World');
return $this->message;
}
}

 
protected function _toHtml() {
$html = parent::_toHtml();

 
if($this->att = $this->getMyCustom() && $this->getMyCustom() != '') {
$html .= '
'.$this->att;
} else {
$html .= '
No Custom Attribute Found';
}

 
return $html;
}
}

The function receiveMessage() just returns “Hello World”
The function _toHtml() is responsible for outputting the template associated with the block. Make sure you run paret::_toHtml and return it as part of any other items returned in that function!

Step: 4
Here we create our template (phtml) file.
app\design\frontend\default\fido\template\example\view.phtml

<?php
 
/**
* Fido view template
*
* @see Fido_Example_Block_View
*
*/
?>
<div>
<span><strong>This is the output of the fido example:</strong></span>
<span style="color:#FF9933;">
<?php
echo $this->receiveMessage();
?>
</span>
</div>

This just outputs some HTML and also runs the receiveMessage() function from our block (view.php).

Two caveats here. By placing our view.phtml file in it’s location, we have created our own theme. You must make sure that

a) Magento knows about your theme (Admin->System->Design)
and

b) If you use the this block in a CMS page, you set the CMS page to use your theme (Admin->CMS->Manage Pages->’Your Page’->Custom Design->Custom Theme drop down)
You’re custom module is now ready for use.
In a cms page, add this to your content:

{{block type="fido_example/view" my_custom="Test" template="example/view.phtml" }}

Or something like this in the Layout Update XML area (Custom Design area in a CMS page)





//this will add your block in the right column
Now you can successfully have your block and the Hello World message being displayed (on your CMS page).


Hope it Helps! Thanks..

Sunday, May 1

How to get product price excluding tax in Magento

In Magento default price shown including Tax.

If you want price excluding Tax then you need to call the following Helper class .

<?php echo $this->helper('checkout')->formatPrice($_product->getPrice())
// For Special Price write this
echo $this->helper('checkout')->formatPrice($_product->getSpecialPrice()) ?> 

Hope it Helps.... Thanks!!!!

Saturday, April 30

How to call the static block inside the CMS Page in Magento

We can easily call the static block in to the CMS Page.
first of all we have to create a static block

Let us suppose we have created the static block with the identifier "myfooter_block"

Now we can call the static block from the CMS Page easily with the help of following code

{{block type="cms/block" block_id="myfooter_block"}}
Hope it helps! thanks..

How to call a static block from template file in Magento

We can call a static block from template file (.phtml) easily.
First we have to create a static block..

Let us consider we have created a static block with the identifier "myfooter_block"

Now we can call the static block from any .phtml file with the help of following code..

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

hope it helps. Thanks

Thursday, April 21

How to get List of Sub Category by main Category ID in Magento

In Magento default the "top.phtml" file shows all category and sub category. can access all category and subcategory in magento by editing "top.phtml"

Here is the location for "top.phtml"
app/design/frontend/your-package/your-theme/template/catalog/navigation/top.phtml

For that we will write the code in top.phtml file

<?php foreach ($this->getStoreCategories() as $_category): ?>
<li>
<a href="<?php echo $this->getCategoryUrl($_category)   ?>"><?php echo $this->htmlEscape($_category->getName())   ?></a>
<?php 
$_catid=$_category->getId();
$category = Mage::getModel('catalog/category')->load($_catid);
$subcategory =  $category->getAllChildren(true);
array_shift($subcategory);
if($subcategory!=null)
{?>
<ul>
<?php
 
foreach ($subcategory as $sub)
{
$sub1 = Mage::getModel('catalog/category')->load( $sub);
?>
<li><a href="<?php echo $sub1->getUrl();?>"><span>
<?php echo $sub1->getName(); ?>
</span></a></li>
<?php } ?>
 
</ul>
<?php  }?>
 
</li>
<?php endforeach ?>

Tuesday, April 19

How to filter all products by attribute value in Magento

Here, I will show how we can filter or fetch products related to any particular attribute and value.

A simple scenario will be filtering products by manufacturer/brand. Suppose, I want to get all products under ‘Samsung’ manufacturer/brand.

For this, you need the attribute code and attribute value ID for which you are fetching products.

To fetch attribute name and value, you can see my previous post here:- How to get attribute name and value in Magento

Now, lets move on to the code. Here is how you can do this:-
/**
 * Get all products related to any particular brand
 * Let us suppose that we are fetching the products related to 'Samsung' brand
 * Let us suppose the Manufacturer ID of Samsung = 3
 */
 
$manufacturerId = 3;
$attributeCode = 'manufacturer';
 
$products = Mage::getModel('catalog/product')
                    ->getCollection()
                    ->addAttributeToFilter($attributeCode, $manufacturerId);
 
// print all products
echo "
"; print_r($products->getItems()); echo "
";

How to get attribute name and value in Magento

Here is the code to get attribute code and value for any product
Let as assume the attribute code is "my_attribute"
/**
 * get attribute collection
 */
$attribute = $_product->getResource()->getAttribute('my_attribute');
/**
 * get attribute type
 */
$attribute->getAttributeType();
/**
 * get attribute Label
 */
$attribute->getFrontendLabel();
/**
 * get attribute default value
 */
$attribute->getDefaultValue();
/**
 * check if the attribute is visible
 */
$attribute->getIsVisible();
/**
 * check if the attribute is required
 */
$attribute->getIsRequired();
/**
 * get attribute value
 */
$attributeValue = Mage::getModel('catalog/product')->load($_product->getId())->getMyAttribute();

Here is the code to fetch value from a select box attribute

$attributeValue = Mage::getModel('catalog/product')
                            ->load($_product->getId())
                            ->getAttributeText('my_attribute');

Load any particular attribute by attribute code
$attributeInfo = Mage::getResourceModel('eav/entity_attribute_collection')
                        ->setCodeFilter(YOUR_ATTRIBUTE_CODE)
                        ->getFirstItem();
 
// echo "
"; print_r($attributeInfo->getData()); echo "
";

Get all option value list for the particular attribute

You can see above that I got attribute information by attribute code. My attribute information is stored as $attributeInfo.

Here is the code to get all option values for my attribute $attributeInfo.

$attributeOptions = $attributeInfo->getSource()->getAllOptions(false);
// echo "
"; print_r($attributeOptions); echo "
";

Get attribute’s option information by option id

I have my attribute as $attributeInfo.
I have my attribute’s option value array as $attributeOptions.

Suppose, I want to get detail information of any option listed in $attributeOptions array. Here is the code to do so
$attributeId = $attributeInfo->getAttributeId();
$optionId = YOUR_ATTRIBUTE_OPTION_ID;
 
$attributeOptionSingle = Mage::getResourceModel('eav/entity_attribute_option_collection')
                                    ->setPositionOrder('asc')
                                    ->setAttributeFilter($attributeId)
                                    ->setIdFilter($optionId)
                                    ->setStoreFilter()
                                    ->load()
                                    ->getFirstItem();
 
// echo "
"; print_r($attributeOptionSingle); echo "
";

Get attribute of particular entity type

Here, I am going to get information about ‘order_id’ attribute of ‘invoice’ entity type.

$entityType = Mage::getModel('eav/config')->getEntityType('invoice');
$entityTypeId = $entityType->getEntityTypeId();
 
$attribute = Mage::getResourceModel('eav/entity_attribute_collection')
                ->setCodeFilter('order_id')
                ->setEntityTypeFilter($entityTypeId)
                ->getFirstItem();
Get attribute options of Configurable product
$confAttributes = $_product->getTypeInstance(true)->getConfigurableAttributesAsArray($_product);

Friday, April 8

Allow Guests To Check Order Status in Magento

Step 1: First thing you have to do is add an API user with a role that has access to all Sales Order information. Generate an API key (any combination of letters and numbers at least 22 (128 bit) characters long) and copy it to Notepad or write it down. You will need it later.

Step 2: Create a New CMS Page that will contain our API code. We usually set the URL identifier to "order-status". Here is what goes in the Content of this new CMS page:
{{block type="core/template" template="cms/order-status-api.phtml"}}


Step 3: create the "order-status-api.phtml" file that will contain our API and HTML display code.
This file needs to be created at /app/design/frontend/default/yourtheme/template/cms/order-status-api.phtml


Here is the code that goes in this file.

<style type="text/css">
.orderStatusTable {
 border:1px solid #CCCCCC;
 font-size:11px;
}
.orderStatusTable td {
padding:8px;
}
.currentStatus {
 font-size: 11px;
 background-color: #eee;
 padding: 10px;
 margin: 0 0 15px 0;
 line-height: 15px;
 border: 1px solid #ccc;
 color: #333;
}
.currentStatus span {
 font-size: 14px;
 line-height: 23px;
 color: #000;
}
</style>
<div class="page-head">
 <h3>Check My Order Status</h3>
</div>

<p>Please enter your order number and email address to see the status of your order.</p>

<form name="" action="/order-status/" method="get">
<table border="0" cellspacing="0" cellpadding="0" class="orderStatusTable">
 <tr>
  <td><strong>Order Number:</strong></td>
  <td><input type="text" name="order_id" id="order_id" value="<?php echo (isset($_GET['order_id'])) ? $_GET['order_id'] : ''; ?>" /></td>
 </tr>
 <tr>
  <td><strong>Email Address:</strong></td>
  <td><input name="email_address" type="text" id="email_address" value="<?php echo (isset($_GET['email_address'])) ? $_GET['email_address'] : ''; ?>" size="30" /></td>
 </tr>
 <tr>
  <td>&nbsp;</td>
  <td><input type="submit" name="submit" value="Submit" /></td>
 </tr>
</table>

</form>

<div class="divider"></div>

<?php
 
 $live = true; //determines verbosity of errors
 
 $error = '';
 $statusMessage = '';
 $trackingNumberMessage = '';
 $shippingMessage = '';
 
 $orderID = '';
 $emailAddress = '';
 
 if(isset($_GET['order_id'])) {
  
  $orderID = trim(preg_replace('/[^0-9]*/', '', $_GET['order_id']));
  $emailAddress = trim($_GET['email_address']);
  
  try {
   
   ini_set("soap.wsdl_cache", "0");
   ini_set("soap.wsdl_cache_enabled", "0");
  
   //******************************************************************/
   
   // change to match your domain name
   $proxy = new SoapClient('http://www.yourdomain.com/api/soap/?wsdl');
   
   //change to your API username/password
   $sessionId = $proxy->login('apiusername', 'apikey');
   
   //******************************************************************/
   
   //find all orders related to this id
   $orderById = $proxy->call($sessionId, 'sales_order.info', $orderID);
   
   $items = $orderById['items'];
   
   if($orderById['customer_email'] == $emailAddress) {
    //we are setting this variable for use later
    $orderLookup = "success";
    if (strtolower($orderById['status']) == "holded") {
     $orderById['status'] = "On Hold";
    }
    $statusMessage = '<span>Your order status is: <strong>'.ucwords(str_replace('_', ' ', $orderById['status'])).'</strong></span>';
    
    if(ucwords(str_replace('_', ' ', $orderById['status'])) == "Processing"){
     $statusMessage .= '<br/><br/><strong>What does this mean?</strong><br/>Processing Time is the time it takes from when you submit your order to when the product leaves the Distribution Center.';
    }
    
   } else {
    $orderLookup = "failure";
    echo "We were unable to find your order information. Please verify your Order Number and Email Address are correct.";
   }
      
   //if the order status is complete we look up shipping information
   if(strtolower($orderById['status']) == "complete" && $orderLookup == "success") {
    

    //we look for all shipments related to this order id using internal magento order id
    $findShipments = $proxy->call($sessionId, 'sales_order_shipment.list', array(array('order_id'=>array('like'=>$orderById['order_id']))));
    
    if (count($findShipments) < 1) { //if $findShipments is not an array
     
     echo "There was an unknown error and your shipment information could not be found. Please contact Customer Service to get the current status of your order.";
     
    } else {
    
     //we pull the increment id for the shipment
     $thisShipmentID = $findShipments[0]['increment_id'];
     
     //now we pull all shipment info that specific shipment id
     $getShipmentInfo = $proxy->call($sessionId, 'sales_order_shipment.info', $thisShipmentID);
     $allowedCarriers = $proxy->call($sessionId, 'sales_order_shipment.getCarriers', $thisShipmentID);
     
     //set each variable
     $shipDate = $getShipmentInfo['created_at'];
     $service = $allowedCarriers[$getShipmentInfo['tracks'][0]['carrier_code']];
     if($service == "Custom Value") $service = "Truck Freight";
     $trackingNumber = $getShipmentInfo['tracks'][0]['number'];
             
     $defaultTimeZone = date_default_timezone_get();
     
     date_default_timezone_set('EST');
     
     //print_r($getShipmentInfo);
     
     if($service == "ups") {
      $trackingNumberMessage = "Tracking Number: <strong><a href='http://wwwapps.ups.com/WebTracking/track?loc=en_US&trackNums=".$trackingNumber."' target='_blank'>".$trackingNumber."</a></strong>";
     } else {
      $trackingNumberMessage = "Tracking Number: <strong>".$trackingNumber."</strong>";
     }
     
     //and echo the data to screen
     $shippingMessage = "Your order was shipped on " . date("l, F jS, Y \\a\\t g:i:s a T", strtotime($shipDate . ' ' . $defaultTimeZone)) . " via " . $service . ".<br/><br/>";
     
         
    } //no errors
   
   }
   
   
   if($orderLookup != "failure"){
   
    echo '<p class="currentStatus">'.$statusMessage.'<br/>'.$trackingNumberMessage.'</p>';
    
    echo $shippingMessage;
    
    echo "<h4>Products in your order:</h4><ul>";
      foreach($items as $item){
       echo "<li>".number_format($item['qty_invoiced'], 0) . " x <strong>" . strtoupper($item['sku']) . "</strong> " . $item['name'] . "</li>";
      }
    echo "</ul>";
   }
   
  } catch (SoapFault $fault) {
   //this is a basic implementation of error checking. I am using try to stop the error from showing a nasty magento error page
   if($fault->faultcode == "100") {
    echo "That Order Number was not found in our system.";
   } elseif ($fault->faultcode == "http") {
    echo "Request timed out. Please try again later.";
   } else {
    //leave this on for testing so we can see SOAP status codes; turn off for live
    if ($live == false) {
     echo "Error $fault->faultcode: $fault->faultstring";
    } else {
     echo "There was an unknown error. Please try again later, or contact us.";
    }
   }   
  }
  
  
  
 } // end if


?>
<p><br /><br /><em>For detailed information regarding the status of your order, please contact our helpful Customer Service Experts.</em></p>

IMPORTANT: You must change two lines in the code to match your settings. These are clearly commented starting at Line 72.

Save the changes you made and upload the file. You should now be able to access the file at http://www.yourdomain.com/order-status.

How to get Total Cart Item and total Price in magento

<?php
  $count = $this->helper('checkout/cart')->getSummaryCount();  //get total items in cart
  $total = $this->helper('checkout/cart')->getQuote()->getGrandTotal(); //get total price
  if($count==0)
  {
    echo $this->__('Items: %s',$count);
  }
  if($count==1)
  {
    echo $this->__(' Item: %s',$count);
  }
  if($count>1)
  {
    echo $this->__(' Items: %s',$count);
  }
  echo $this->__(' Total: %s', $this->helper('core')->formatPrice($total, false));
?>