Skip to content

Instantly share code, notes, and snippets.

@avocadoslab
Forked from manojiksula/magento.md
Created November 7, 2016 17:12
Show Gist options
  • Save avocadoslab/7048034a31505238de72e9cee7a2f63b to your computer and use it in GitHub Desktop.
Save avocadoslab/7048034a31505238de72e9cee7a2f63b to your computer and use it in GitHub Desktop.
Magento Code Snippet

Common

Magento : Get Base Url , Skin Url , Media Url , Js Url , Store Url and Current Url

Get Url in phtml files

  1. Get Base Url :
	Mage::getBaseUrl();
  1. Get Skin Url :
	Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_SKIN);

(a) Unsecure Skin Url :

	$this->getSkinUrl('images/imagename.jpg');

(b) Secure Skin Url :

	$this->getSkinUrl('images/imagename.gif', array('_secure'=>true));
  1. Get Media Url :
	Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA);
  1. Get Js Url :
	Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_JS);
  1. Get Store Url :
	Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB);
  1. Get Current Url
	Mage::helper('core/url')->getCurrentUrl();

Get Url in cms pages or static blocks

  1. Get Base Url :
{{store url=""}}
  1. Get Skin Url :
{{skin url='images/imagename.jpg'}}
  1. Get Media Url :
{{media url='/imagename.jpg'}}
  1. Get Store Url :
{{store url='mypage.html'}}

Run Magento Code Externally

<?php
require_once('app/Mage.php'); //Path to Magento
umask(0);
Mage::app();
// Run you code here
?>

$_GET, $_POST & $_REQUEST Variables

<?php

	// get all parameters
	$allParams = Mage::app()->getRequest()->getParams();
	// $_GET
	$productId = Mage::app()->getRequest()->getParam('product_id');
	// The second parameter to getParam allows you to set a default value which is returned if the GET value isn't set
	$productId = Mage::app()->getRequest()->getParam('product_id', 44);
	$postData = Mage::app()->getRequest()->getPost();
	// You can access individual variables like...
	$productId = $postData['product_id']);
?>

Magento Custom Notification Message

<?php	
	### Notice ###
	Mage::getSingleton('core/session')->addNotice('Notice message');

	### Success ###
	Mage::getSingleton('core/session')->addSuccess('Success message'); 

	### Error ###
	Mage::getSingleton('core/session')->addError('Error message'); 

	### Warning (admin only) ###
	Mage::getSingleton('adminhtml/session')->addWarning('Warning message'); 
?>

Get Currency Symbol

<?php
	 Mage::app()->getLocale()->currency(Mage::app()->getStore()->getCurrentCurrencyCode())->getSymbol(); 
?>

Format Price

<?php
    $formattedPrice = Mage::helper('core')->currency($_finalPrice,true,false);
?>

Get Currency Code

<?php
    Mage::app()->getStore()->getCurrentCurrencyCode();
?>

Changing price from any one currency to another

<?php
    $from = 'USD';
    $to = 'NPR';
    $price = 10;

    $newPrice = Mage::helper('directory')->currencyConvert($price, $from, $to);
?>

Track Visitor’s Information

<?php
   $visitorData = Mage::getSingleton('core/session')->getVisitorData();
    print_r($visitorData);
?>

Convert Price from Current Currency to Base Currency and vice-versa

<?php
    $baseCurrencyCode = Mage::app()->getStore()->getBaseCurrencyCode();
    $currentCurrencyCode = Mage::app()->getStore()->getCurrentCurrencyCode();
    $price = 100;

    // convert price from current currency to base currency
    $priceOne = Mage::helper('directory')->currencyConvert($price, $currentCurrencyCode, $baseCurrencyCode); 

    // convert price from base currency to current currency
    $priceTwo = Mage::helper('directory')->currencyConvert($price, $baseCurrencyCode, $currentCurrencyCode);
?>

Magento Session

set custom session in frontend

// To Set the Session 
Mage::getSingleton('core/session')->setMySessionVariable('MyValue'); 

// To Get the Session
$myValue  =  Mage::getSingleton('core/session')->getMySessionVariable();
echo $myValue;

// To Unset the session

Mage::getSingleton('core/session')->unsMySessionVariable();

How to Use customer or core session in frontend. Use adminhtml session in the backend.

Core Session :- Mage::getSingleton('core/session');
Customer Session :- Mage::getSingleton('customer/session');
Admin Session :- Mage::getSingleton('adminhtml/session');
Shopping Cart Session :-Mage::getSingleton('checkout/session')->getQuote();

Working with Collection

	$_products = Mage::getModel('catalog/product')->getCollection();

For EAV Tables

	## Equals: eq ##

	$_products->addAttributeToFilter('status', array('eq' => 1));

	## Not Equals - neq ##

	$_products->addAttributeToFilter('sku', array('neq' => 'test-product'));

	## Like - like ##

	$_products->addAttributeToFilter('sku', array('like' => 'UX%'));

	One thing to note about like is that you can include SQL wildcard characters such as the percent sign.

	## Not Like - nlike ##

	$_products->addAttributeToFilter('sku', array('nlike' => 'err-prod%'));

	## In - in ##

	$_products->addAttributeToFilter('id', array('in' => array(1,4,98)));

	When using in, the value parameter accepts an array of values.

	## Not In - nin ##

	$_products->addAttributeToFilter('id', array('nin' => array(1,4,98)));

	## NULL - null ##

	$_products->addAttributeToFilter('description', 'null');

	## Not NULL - notnull ##

	$_products->addAttributeToFilter('description', 'notnull');

	## Greater Than - gt ##

	$_products->addAttributeToFilter('id', array('gt' => 5));

	## Less Than - lt ##

	$_products->addAttributeToFilter('id', array('lt' => 5));

	## Greater Than or Equals To- gteq ##

	$_products->addAttributeToFilter('id', array('gteq' => 5));

	## Less Than or Equals To - lteq ##

	$_products->addAttributeToFilter('id', array('lteq' => 5));

For Single Tables

//for AND
    $collection = Mage::getModel('sales/order')->getCollection()
    ->addAttributeToSelect('*')
    ->addFieldToFilter('my_field1', 'my_value1')
    ->addFieldToFilter('my_field2', 'my_value2');

    echo $collection->getSelect()->__toString();

//for OR - please note 'attribute' is the key name and must remain the same, only replace //the value (my_field1, my_field2) with your attribute name


	$collection = Mage::getModel('sales/order')->getCollection()
	->addAttributeToSelect('*')
	->addFieldToFilter(
		array(
		array('attribute'=>'my_field1','eq'=>'my_value1'),
		array('attribute'=>'my_field2', 'eq'=>'my_value2')
	)
	);

Retrieve Magento Core Configuration variables on the Magento frontend

Mage::getStoreConfig('myappgeneral/current_time/second', $store_id)

Clear cache/reindex

<?php
// clear cache
Mage::app()->removeCache('catalog_rules_dirty');
// reindex prices
Mage::getModel('index/process')->load(2)->reindexEverything();
/*
1 = Product Attributes
2 = Product Attributes
3 = Catalog URL Rewrites
4 = Product Flat Data
5 = Category Flat Data
6 = Category Products
7 = Catalog Search Index
8 = Tag Aggregation Data
9 = Stock Status
*/
?>

Which page is this? – Magento

Detect Home Page – Magento

if($this->getIsHomePage())
{
  // Home page
}

Detect Category Page – Magento

if (Mage::registry('current_category')) 
{
  // category page
}

Detect Category Page – Magento

if (Mage::registry('current_category')) 
{
  // Category Name
  echo Mage::registry('current_category')->getName();

  // Category ID
  echo Mage::registry('current_category')->getId();
}

Detect CMS Page – Magento

if(Mage::app()->getFrontController()->getRequest()->getRouteName() == 'cms')
{
  // CMS page
}

Get CMS page name if current one is the CMS page.

if(Mage::app()->getFrontController()->getRequest()->getRouteName() == 'cms')
{
  echo Mage::getSingleton('cms/page')->getIdentifier();
}

Detect Product Detail Page – Magento

if(Mage::app()->getFrontController()->getRequest()->getRequestedActionName() == 'configure')
{
  // Product Configuration page
}

Detect Cart Page – Magento

 $request = $this->getRequest();
 $module = $request->getModuleName();
 $controller = $request->getControllerName();
 $action = $request->getActionName();
 if($module == 'checkout' && $controller == 'cart' && $action == 'index')
 {
   //Cart Page
 }

CMS Page

Call a PHTML file within a CMS page Magento

{{ block type="core/template" name="mycstompage" template="SkyMagento/mycustompage.phtml" }}

Call cms static block within a CMS page Magento

{{block type="cms/block" block_id="your_block_id"}}

Call Static Block in phtml

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

Call static block using layout(XML)

<default>
	<cms_page> <!-- need to be redefined for your needs -->
		<reference name="content">
			<block type="cms/block" name="cms_newest_product" as="cms_newest_product">
				<action method="setBlockId"><block_id>newest_product</block_id></action>
			</block>
		</reference>
	</cms_page>
</default>

In your phtml template call file as mention:

echo $this->getChildHtml('newest_product');

Inject any block programmatically in any page any where

<?php 
  echo $this->getLayout()->createBlock('core/template')->setTemplate('goodtest/test.phtml')->toHtml();
?>

Add block in CMS page using layout

go to design and change the layout what you want

to add left column in cms page just add belw code in layout

<reference name="left">
	<block type="cms/block" name="sample_block" before="-">
		<action method="setBlockId"><block_id>sample_block</block_id></action>
	</block>
</reference>

to add right column in cms page just add belw code in layout

<reference name="right">
	<block type="cms/block" name="sample_block" before="-">
		<action method="setBlockId"><block_id>sample_block</block_id></action>
	</block>
</reference>

Displaying Products in a Static Block

{{block type="catalog/product_list" name="product_list" category_id="3" column_count="6" count="6"
limit="4" mode="grid" template="catalog/product/list.phtml"}}

Debugging

Get methods of an object

First, use get_class to get the name of an object's class.

<?php $class_name = get_class($object); ?>

Then, pass that get_class_methods to get a list of all the callable methods on an object

<?php
$class_name = get_class($object);
$methods = get_class_methods($class_name);
foreach($methods as $method)
{
    var_dump($method);
}
?>

Log to custom file

<?php Mage::log('Your Log Message', Zend_Log::INFO, 'your_log_file.log'); ?>

Print Query of current collection

<?php 
	$collection = Mage::getModel('modulename/modelname')->getCollection();
	echo $collection->printLogQuery(true);
	echo $collection->getSelect();
?>

Debug using zend

<?php Zend_Debug::dump($thing_to_debug, 'debug'); ?>

Try catch

try {
    // code to run

} catch (Exception $e) { 
    var_dump($e->getMessage());
}

Customer

Check if customer is logged in

 $_customer = Mage::getSingleton('customer/session')->isLoggedIn();
    if ($_customer) {}

Get Customer Shipping/Billing Address

<?php
    $customerAddressId = Mage::getSingleton('customer/session')->getCustomer()->getDefaultShipping();
    if ($customerAddressId){
        $address = Mage::getModel('customer/address')->load($customerAddressId);
    }
?>

Get Details of logged in user in Magento

	$customer = Mage::getSingleton('customer/session')->getCustomer();
	$customer->getPrefix();
	$customer->getName(); // Full Name
	$customer->getFirstname(); // First Name
	$customer->getMiddlename(); // Middle Name
	$customer->getLastname(); // Last Name
	$customer->getSuffix();

	// All other customer data
	$customer->getWebsiteId(); // ID
	$customer->getEntityId(); // ID
	$customer->getEntityTypeId(); // ID
	$customer->getAttributeSetId(); // ID
	$customer->getEmail();
	$customer->getGroupId(); // ID
	$customer->getStoreId(); // ID
	$customer->getCreatedAt(); // yyyy-mm-ddThh:mm:ss+01:00
	$customer->getUpdatedAt(); // yyyy-mm-dd hh:mm:ss
	$customer->getIsActive(); // 1
	$customer->getDisableAutoGroupChange();
	$customer->getTaxvat();
	$customer->getPasswordHash();
	$customer->getCreatedIn(); // Admin
	$customer->getGender(); // ID
	$customer->getDefaultBilling(); // ID
	$customer->getDefaultShipping(); // ID
	$customer->getDob(); // yyyy-mm-dd hh:mm:ss
	$customer->getTaxClassId(); // ID

Get logged in customer id and email

	$customer = Mage::getSingleton('customer/session')->getCustomer();
	$customer_id = $customer->getId();
	$customer_email = $customer->getEmail();

Programmatically adding new customers to the Magento store

	$websiteId = Mage::app()->getWebsite()->getId();
	$store = Mage::app()->getStore();
	 
	$customer = Mage::getModel("customer/customer");
	$customer   ->setWebsiteId($websiteId)
	            ->setStore($store)
	            ->setFirstname('John')
	            ->setLastname('Doe')
	            ->setEmail('jd1@ex.com')
	            ->setPassword('somepassword');
	 
	try{
	    $customer->save();
	}
	catch (Exception $e) {
	    Zend_Debug::dump($e->getMessage());
	}

Product Page

Load product by id or sku

<?php
	$_product_1 = Mage::getModel('catalog/product')->load(12);
	$_product_2 = Mage::getModel('catalog/product')->loadByAttribute('sku','cordoba-classic-6-String-guitar');
?>

Get the current category/product/cms page

<?php
	$currentCategory = Mage::registry('current_category');
	$currentProduct = Mage::registry('current_product');
	$currentCmsPage = Mage::registry('cms_page');
?>

Is product purchasable?

<?php if($_product->isSaleable()) { // do stuff } ?>

Get Product URL In Magento

<?php 
 $_product = Mage::getModel('catalog/product')->load(4); 
 echo $_product->getProductUrl();
?>

Get Stock of Product in Magento

<?php 
 $_product = Mage::getModel('catalog/product')->load(4); 
 $stock = Mage::getModel('cataloginventory/stock_item')->loadByProduct($_product);
 echo $stock->getQty();
 echo $stock->getMinQty();
 echo $stock->getMinSaleQty();

?>

Getting Configurable Attributes (Super Attributes) of a Configurable Product

<?php 
    /**
    * Load Product you want to get Super attributes of
    */
    $product=Mage::getModel("catalog/product")->load(52520);

    /**
    * Get Configurable Type Product Instace and get Configurable attributes collection
    */
    $configurableAttributeCollection=$product->getTypeInstance()->getConfigurableAttributes();

    /**
    * Use the collection to get the desired values of attribute
    */
    foreach($configurableAttributeCollection as $attribute){
        echo "Attr-Code:".$attribute->getProductAttribute()->getAttributeCode()."<br/>";
        echo "Attr-Label:".$attribute->getProductAttribute()->getFrontend()->getLabel()."<br/>";
        echo "Attr-Id:".$attribute->getProductAttribute()->getId()."<br/>";
        var_dump($_attribute->debug()); // returns the set of values you can use the get magic method on
    }
?>

Load Products by Category ID

<?php
$_category = Mage::getModel('catalog/category')->load(47);
$_productCollection = $_category->getProductCollection();
if($_productCollection->count()) {
    foreach( $_productCollection as $_product ):
        echo $_product->getProductUrl();
        echo $this->getPriceHtml($_product, true);
        echo $this->htmlEscape($_product->getName());
    endforeach;
}
?>

Create a Country Drop Down in the Frontend of Magento

<?php
$_countries = Mage::getResourceModel('directory/country_collection')
                                    ->loadData()
                                    ->toOptionArray(false) ?>
<?php if (count($_countries) > 0): ?>
    <select name="country" id="country">
        <option value="">-- Please Select --</option>
        <?php foreach($_countries as $_country): ?>
            <option value="<?php echo $_country['value'] ?>">
                <?php echo $_country['label'] ?>
            </option>
        <?php endforeach; ?>
    </select>
<?php endif; ?>

Get product image

<?php
	$_product = Mage::getModel('catalog/product')->load(4); 
	// input is $_product and result is iterating child products
	$this->helper('catalog/image')->init($_product, 'image');
?>

Get actual price and special price of a product

<?php
    $_productId = 52;
    $_product = Mage::getModel('catalog/product')->load($_productId);

    // without currency sign
    $_actualPrice = number_format($_product->getPrice(), 2);
    // with currency sign
    $_formattedActualPrice = Mage::helper('core')->currency(number_format($_product->getPrice(), 2),true,false);

    // without currency sign
    $_specialPrice = $_product->getFinalPrice();
    // with currency sign
    $_formattedSpecialPrice = Mage::helper('core')->currency(number_format($_product->getFinalPrice(), 2),true,false);
?>

Downsize large product images but not enlarge small images

<?php
    $this->helper('catalog/image')
        ->init($_product, 'image')
        ->keepFrame(false) // avoids getting the small image in original size on a solid background color presented (can be handy not to break some layouts)
        ->constrainOnly(true) // avoids getting small images bigger
        ->resize(650); // sets the desired width and the height accordingly (proportional by default)
?>

Add block after add to cart in magento using layout

<catalog_product_view>
 
    <reference name="product.info.container1" after="-">
        <action method="setTemplate">
                <template>pincode/index.phtml</template>
        </action>
        <block type="catalog/product_view" name="original_addtocart"
           as="original_addtocart" template="pincode/index.phtml"/>
    </reference>
</catalog_product_view>

Get Configurable product's Child products

<?php
// input is $_product and result is iterating child products
	$childProducts = Mage::getModel('catalog/product_type_configurable')->getUsedProducts(null, $product);
?>

Return Product Attributes

<?php
	$_product->getThisattribute();
	
	$_product->getAttributeText('thisattribute');
	
	$_product->getResource()->getAttribute('thisattribute')->getFrontend()->getValue($_product);
	
	$_product->getData('thisattribute');
	
	// The following returns the option IDs for an attribute that is a multiple-select field: 
	$_product->getData('color'); // i.e. 456,499
	
	// The following returns the attribute object, and instance of Mage_Catalog_Model_Resource_Eav_Attribute: 
	$_product->getResource()->getAttribute('color'); // instance of Mage_Catalog_Model_Resource_Eav_Attribute
	
	// The following returns an array of the text values for the attribute: 
	$_product->getAttributeText('color') // Array([0]=>'red', [1]=>'green')
	
	// The following returns the text for the attribute
	if ($attr = $_product->getResource()->getAttribute('color')):
	    echo $attr->getFrontend()->getValue($_product); // will display: red, green
	endif;
?>

Get Parent product's by Child products

<?php
// pass the sku of the child product
public function getParentproduct(int $sku){

	$product = Mage::getModel('catalog/product');
	$productobject = $product->load($product->getIdBySku($sku));
	$ProductId = $product->getIdBySku($sku);
	$helperdata = Mage::helper("modulename/data");

	if($productobject->getTypeId() == 'simple'){
 		//product_type_grouped
		$parentIds = Mage::getModel('catalog/product_type_grouped')
		->getParentIdsByChild($productobject->getId());


		//product_type_configurable
		if(!$parentIds){
			$parentIds = Mage::getModel('catalog/product_type_configurable')
			->getParentIdsByChild($productobject->getId());

		}
 		//product_type_bundle
		if(!$parentIds){
			$parentIds = Mage::getModel('bundle/product_type')
			->getParentIdsByChild($productobject->getId());

		}

	}
	return $parentIds;
}
?>

Category Page

Load category by id

<?php
$_category = Mage::getModel('catalog/category')->load(89);
$_category_url = $_category->getUrl();
?>

Get The Root Category In Magento

<?php
$rootCategoryId = Mage::app()->getStore()->getRootCategoryId();
$_category = Mage::getModel('catalog/category')->load($rootCategoryId);
// You can then get all of the top level categories using:
$_subcategories = $_category->getChildrenCategories();
?>

Get Category URL In Magento

<?php 
 $category = Mage::getModel('catalog/category')->load(4); 
 echo $category->getUrl();
?>

Category Navigation Listings in Magento

Make sure the block that you’re working is of the type catalog/navigation. If you’re editing catalog/navigation/left.phtml then you should be okay.

<div id="leftnav">
    <?php $helper = $this->helper('catalog/category') ?>
    <?php $categories = $this->getStoreCategories() ?>
    <?php if (count($categories) > 0): ?>
        <ul id="leftnav-tree" class="level0">
            <?php foreach($categories as $category): ?>
                <li class="level0<?php if ($this->isCategoryActive($category)): ?> active<?php endif; ?>">
                    <a href="<?php echo $helper->getCategoryUrl($category) ?>"><span><?php echo $this->escapeHtml($category->getName()) ?></span></a>
                    <?php if ($this->isCategoryActive($category)): ?>
                        <?php $subcategories = $category->getChildren() ?>
                        <?php if (count($subcategories) > 0): ?>
                            <ul id="leftnav-tree-<?php echo $category->getId() ?>" class="level1">
                                <?php foreach($subcategories as $subcategory): ?>
                                    <li class="level1<?php if ($this->isCategoryActive($subcategory)): ?> active<?php endif; ?>">
                                        <a href="<?php echo $helper->getCategoryUrl($subcategory) ?>"><?php echo $this->escapeHtml(trim($subcategory->getName(), '- ')) ?></a>
                                    </li>
                                <?php endforeach; ?>
                            </ul>
                            <script type="text/javascript">decorateList('leftnav-tree-<?php echo $category->getId() ?>', 'recursive')</script>
                        <?php endif; ?>
                    <?php endif; ?>
                </li>
            <?php endforeach; ?>
        </ul>
        <script type="text/javascript">decorateList('leftnav-tree', 'recursive')</script>
    <?php endif; ?>
</div>

Cart Page

Magento: Get Sales Quote & Order in both Frontend and Admin

## Get Sales Quote in Frontend ##

Mage::getSingleton('checkout/session')->getQuote(); 

## Get Sales Quote in Admin ##

$quote = Mage::getSingleton('adminhtml/session_quote')->getQuote();

## Get Latest Order in Frontend ##

$orderId = Mage::getSingleton('checkout/session')->getLastRealOrderId();
$order = Mage::getModel('sales/order')->loadByIncrementId($orderId);

## Get Latest Order in Admin ##

$order = Mage::getModel('sales/order')->getCollection()
                     ->setOrder('created_at','DESC')
                     ->setPageSize(1)
                     ->setCurPage(1)
                     ->getFirstItem();  

Get all items information in cart

$quote  = Mage::getSingleton('checkout/session')->getQuote();

$items = $quote->getAllItems();

foreach($items as $item) {
	echo 'ID: '.$item->getProductId().'<br />';
	echo 'Name: '.$item->getName().'<br />';
	echo 'Sku: '.$item->getSku().'<br />';
	echo 'Quantity: '.$item->getQty().'<br />';
	echo 'Price: '.$item->getPrice().'<br />';
	echo "<br />";
}

Check if there are any items in cart or not

$totalItemsInCart = Mage::helper('checkout/cart')->getItemsCount();

Get First and/or Last item from collection

$firstItem = $collection->getFirstItem(); Mage::log($firstItem->getData());
$lastItem = $collection->getLastItem(); Mage::log($lastItem->getData());

Total items added in cart

<?php
    Mage::getModel('checkout/cart')->getQuote()->getItemsCount();
    Mage::getSingleton('checkout/session')->getQuote()->getItemsCount();
?>

Total Quantity added in cart

<?php
    Mage::getModel('checkout/cart')->getQuote()->getItemsQty();
    Mage::getSingleton('checkout/session')->getQuote()->getItemsQty();
?>

Sub Total for item added in cart

<?php
    Mage::getModel('checkout/cart')->getQuote()->getSubtotal();
    Mage::getSingleton('checkout/session')->getQuote()->getSubtotal();
?>

Grand total for item added in cart

<?php
    Mage::helper('checkout')->formatPrice(Mage::getModel('checkout/cart')->getQuote()->getGrandTotal());
    Mage::helper('checkout')->formatPrice(Mage::getSingleton('checkout/session')->getQuote()->getGrandTotal());
?>

Sub total of cart inkl tax without shipping

<?php
    $quote = Mage::getSingleton('checkout/session')->getQuote();
    $items = $quote->getAllItems();
    foreach ($items as $item) {
        $priceInclVat += $item->getRowTotalInclTax();
    }
    Mage::helper('checkout')->formatPrice($priceInclVat);
?>

Get number of items in cart and total quantity in cart

<?php
    $totalItems = Mage::getModel('checkout/cart')->getQuote()->getItemsCount();
    $totalQuantity = Mage::getModel('checkout/cart')->getQuote()->getItemsQty();
?>

Sales Order

Load order by id and increment id

To load by Order id you would just call load:

$order = Mage::getModel('sales/order')->load(24999); //use an entity id here

To load an order by increment id one would do:

$order = Mage::getModel('sales/order')->loadByIncrementId('10000001'); //use a real increment order

Get order details by order id

To load by Order id you would just call load:

echo '<pre>';

$order = Mage::getModel('sales/order')->load(24999); //use an entity id here

$orderData  = $order->getData();

print_r($orderData);

Magento – get all ordered items of the order

<?php 
	$order_id = 2314; //use your own order id 
	$order = Mage::getModel("sales/order")->load($order_id); //load order by order id 
	$ordered_items = $order->getAllItems(); 
	foreach($ordered_items as $item){     //item detail     
		echo $item->getItemId(); //product id     
		echo $item->getSku();     
		echo $item->getQtyOrdered(); //ordered qty of item     
		echo $item->getName();     // etc.
	} 
?>

Magento – change cancelled order to processing programmtially

<?php 
	$incrementId = '100057506'; //replace this with the increment id of your actual order
	$order = Mage::getModel('sales/order')->loadByIncrementId($incrementId);

	$order->setState(Mage_Sales_Model_Order::STATE_PROCESSING);
	$order->setStatus('processing');
	$order->setBaseDiscountCanceled(0);
	$order->setBaseShippingCanceled(0);
	$order->setBaseSubtotalCanceled(0);
	$order->setBaseTaxCanceled(0);
	$order->setBaseTotalCanceled(0);
	$order->setDiscountCanceled(0);
	$order->setShippingCanceled(0);
	$order->setSubtotalCanceled(0);
	$order->setTaxCanceled(0);
	$order->setTotalCanceled(0);

	foreach($order->getAllItems() as $item){
		$item->setQtyCanceled(0);
		$item->setTaxCanceled(0);
		$item->setHiddenTaxCanceled(0);
		$item->save();
	}


	$order->save();
?>

Checkout Page

Get all active payment methods

$activePayMethods = Mage::getModel('payment/config')->getActiveMethods();

Get all active shipping carriers

$activeCarriers = Mage::getSingleton('shipping/config')->getActiveCarriers();

Get order information on success.phtml

<?php
	$_customerId = Mage::getSingleton('customer/session')->getCustomerId();
	$lastOrderId = Mage::getSingleton('checkout/session')->getLastOrderId();
	$order = Mage::getSingleton('sales/order');
	$order->load($lastOrderId);
	$_totalData =$order->getData();
	$_grand = $_totalData['grand_total'];
?>

Admin Panel

Magento: Mass Exclude/Unexclude Images

By default, Magento will check the 'Exclude' box for you on all imported images, making them not show up as a thumbnail under the main product image on the product view.

# Mass Unexclude
UPDATE`catalog_product_entity_media_gallery_value` SET `disabled` = '0' WHERE `disabled` = '1';
# Mass Exclude
UPDATE`catalog_product_entity_media_gallery_value` SET `disabled` = '1' WHERE `disabled` = '0';

RESET

Reset Sales order

SET FOREIGN_KEY_CHECKS=0;
TRUNCATE `sales_flat_creditmemo`;
TRUNCATE `sales_flat_creditmemo_comment`;
TRUNCATE `sales_flat_creditmemo_grid`;
TRUNCATE `sales_flat_creditmemo_item`;
TRUNCATE `sales_flat_invoice`;
TRUNCATE `sales_flat_invoice_comment`;
TRUNCATE `sales_flat_invoice_grid`;
TRUNCATE `sales_flat_invoice_item`;
TRUNCATE `sales_flat_order`;
TRUNCATE `sales_flat_order_address`;
TRUNCATE `sales_flat_order_grid`;
TRUNCATE `sales_flat_order_item`;
TRUNCATE `sales_flat_order_payment`;
TRUNCATE `sales_flat_order_status_history`;
TRUNCATE `sales_flat_quote`;
TRUNCATE `sales_flat_quote_address`;
TRUNCATE `sales_flat_quote_address_item`;
TRUNCATE `sales_flat_quote_item`;
TRUNCATE `sales_flat_quote_item_option`;
TRUNCATE `sales_flat_quote_payment`;
TRUNCATE `sales_flat_quote_shipping_rate`;
TRUNCATE `sales_flat_shipment`;
TRUNCATE `sales_flat_shipment_comment`;
TRUNCATE `sales_flat_shipment_grid`;
TRUNCATE `sales_flat_shipment_item`;
TRUNCATE `sales_flat_shipment_track`;
TRUNCATE `sales_invoiced_aggregated`;
TRUNCATE `sales_invoiced_aggregated_order`;
TRUNCATE `sales_order_aggregated_created`;
TRUNCATE `sendfriend_log`;
TRUNCATE `tag`;
TRUNCATE `tag_relation`;
TRUNCATE `tag_summary`;
TRUNCATE `wishlist`;
TRUNCATE `log_quote`;
TRUNCATE `report_event`;
ALTER TABLE `sales_flat_creditmemo` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_creditmemo_comment` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_creditmemo_grid` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_creditmemo_item` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_invoice` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_invoice_comment` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_invoice_grid` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_invoice_item` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_order` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_order_address` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_order_grid` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_order_item` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_order_payment` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_order_status_history` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_quote` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_quote_address` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_quote_address_item` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_quote_item` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_quote_item_option` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_quote_payment` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_quote_shipping_rate` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_shipment` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_shipment_comment` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_shipment_grid` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_shipment_item` AUTO_INCREMENT=1;
ALTER TABLE `sales_flat_shipment_track` AUTO_INCREMENT=1;
ALTER TABLE `sales_invoiced_aggregated` AUTO_INCREMENT=1;
ALTER TABLE `sales_invoiced_aggregated_order` AUTO_INCREMENT=1;
ALTER TABLE `sales_order_aggregated_created` AUTO_INCREMENT=1;
ALTER TABLE `sendfriend_log` AUTO_INCREMENT=1;
ALTER TABLE `tag` AUTO_INCREMENT=1;
ALTER TABLE `tag_relation` AUTO_INCREMENT=1;
ALTER TABLE `tag_summary` AUTO_INCREMENT=1;
ALTER TABLE `wishlist` AUTO_INCREMENT=1;
ALTER TABLE `log_quote` AUTO_INCREMENT=1;
ALTER TABLE `report_event` AUTO_INCREMENT=1;

SET FOREIGN_KEY_CHECKS=1; 

Reset Customer Table

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;

Clean Log Tables

SET FOREIGN_KEY_CHECKS=0;
TRUNCATE `log_customer`;
TRUNCATE `log_visitor`;
TRUNCATE `log_visitor_info`;
TRUNCATE `log_visitor_online`;
TRUNCATE `log_quote`;
TRUNCATE `log_summary`;
TRUNCATE `log_summary_type`;
TRUNCATE `log_url`;
TRUNCATE `log_url_info`;
TRUNCATE `sendfriend_log`;
TRUNCATE `report_event`;
TRUNCATE `dataflow_batch_import`;
TRUNCATE `dataflow_batch_export`;
TRUNCATE `index_process_event`;
TRUNCATE `index_event`;
ALTER TABLE `log_customer` AUTO_INCREMENT=1;
ALTER TABLE `log_visitor` AUTO_INCREMENT=1;
ALTER TABLE `log_visitor_info` AUTO_INCREMENT=1;
ALTER TABLE `log_visitor_online` AUTO_INCREMENT=1;
ALTER TABLE `log_quote` AUTO_INCREMENT=1;
ALTER TABLE `log_summary` AUTO_INCREMENT=1;
ALTER TABLE `log_url_info` AUTO_INCREMENT=1;
ALTER TABLE `sendfriend_log` AUTO_INCREMENT=1;
ALTER TABLE `report_event` AUTO_INCREMENT=1;
ALTER TABLE `dataflow_batch_import` AUTO_INCREMENT=1;
ALTER TABLE `dataflow_batch_export` AUTO_INCREMENT=1;
ALTER TABLE `index_event` AUTO_INCREMENT=1;
SET FOREIGN_KEY_CHECKS=1;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment