HTML/JavaScript

Tuesday, August 27, 2013

Generate Category Tree Recursively

In this blog we will see how generate a category tree, recursively showing all categories and sub categories.

The code is given below, will explain the code line by line

<?php
$rootcatId= Mage::app()->getStore()->getRootCategoryId();
$categories = Mage::getModel('catalog/category')->getCategories($rootcatId);
function  get_categories($categories) {
    $array= '<ul>';
    foreach($categories as $category) {
           $cat = Mage::getModel('catalog/category')->load($category->getId());
        $count = $cat->getProductCount();
        $array .= '<li>'.
        '<a href="' . Mage::getUrl($cat->getUrlPath()). '">' .
                  $category->getName() . "(".$count.")</a>\n";
        if($category->hasChildren()) {
            $children = Mage::getModel('catalog/category')->getCategories($category->getId());
             $array .=  get_categories($children);
            }
         $array .= '</li>';
    }
    return  $array . '</ul>';
}
echo  get_categories($categories); ?>

Explanation of the code step by step:

  $rootcatId= Mage::app()->getStore()->getRootCategoryId();

This function gives return the Root Catalog Id of your current store. Usually the value is 2 but its always better to use this function.

$categories = Mage::getModel('catalog/category')->getCategories($rootcatId);

This function returns all sub categories of the parent category. This function is defined in Mage_Catalog_Model_Category. the definition is

/**
     * Retrieve categories by parent
     *
     * @param int $parent
     * @param int $recursionLevel
     * @param bool $sorted
     * @param bool $asCollection
     * @param bool $toLoad
     * @return mixed
     */
    public function getCategories($parent, $recursionLevel = 0, $sorted=false, $asCollection=false, $toLoad=true);

function  get_categories($categories) { //This is the recursive function created and here we pass the a collection of categories.
$array= '<ul>';  //$array is a variable to store all the category detail .
foreach($categories as $category) {
         $cat = Mage::getModel('catalog/category')->load($category->getId());
        $count = $cat->getProductCount(); //$count the total no of products in the category
        $array .= '<li>'.'<a href="' . Mage::getUrl($cat->getUrlPath()). '">' . $category->getName() . "(".$count.")</a>\n"; //In this line we get an a link for the product and product count of that category
        if($category->hasChildren()) {  if category has children or not. If yes then it proceed in inside loop.
             $children = Mage::getModel('catalog/category')->getCategories($category-> getId()); // $children get a list of all subcategories
            $array .=  get_categories($children); //recursive call the get_categories function again.
            }
         $array .= '</li>';
    }
    return  $array . '</ul>';
}
echo  get_categories($categories); //echo all categories in the website, with number of products

You can use your own css and javascript to design the html generated.
- See more at: http://excellencetechnologies.co.in/Telephonia/blog/magento-generate-category-tree-recursively/#sthash.vDwZfAn4.dpuf

Magento: How to get most viewed products?

Here, I will show you the code to get the most viewed products in Magento. The function addViewsCount() filters the products with their views count.

Here is the code:-

Get overall Most viewed products
public function getMostViewedProducts()
{     
    /**
     * Number of products to display
     * You may change it to your desired value
     */
    $productCount = 5;
    
    /**
     * Get Store ID
     */
    $storeId    = Mage::app()->getStore()->getId();     
    
    /**
     * Get most viewed product collection
     */
    $products = Mage::getResourceModel('reports/product_collection')
        ->addAttributeToSelect('*')    
        ->setStoreId($storeId)
        ->addStoreFilter($storeId)
        ->addViewsCount()
        ->setPageSize($productCount);
    
    Mage::getSingleton('catalog/product_status')
            ->addVisibleFilterToCollection($products);
    Mage::getSingleton('catalog/product_visibility')
            ->addVisibleInCatalogFilterToCollection($products);
    
    return $products;
}

Get Most viewed products for current category
public function getMostViewedProducts()

    // number of products to display
    $productCount = 5;
    
    // store ID
    $storeId    = Mage::app()->getStore()->getId();     
    
    // get most viewed products for current category
    $products = Mage::getResourceModel('reports/product_collection')
        ->addAttributeToSelect('*')    
        ->setStoreId($storeId)
        ->addStoreFilter($storeId)
        ->addViewsCount()
        ->addCategoryFilter(Mage::registry('current_category'))
        ->setPageSize($productCount);
    
    Mage::getSingleton('catalog/product_status')
            ->addVisibleFilterToCollection($products);
    Mage::getSingleton('catalog/product_visibility')
            ->addVisibleInCatalogFilterToCollection($products);
    
    return $products;
}

Get Most viewed products for last 30 days
public function getMostViewedProducts()

    // number of products to display
    $productCount = 5;
    
    // store ID
    $storeId    = Mage::app()->getStore()->getId();
    
    // get today and last 30 days time
    $today = time();
    $last = $today - (60*60*24*30);

    $from = date("Y-m-d", $last);
    $to = date("Y-m-d", $today);
    
    // get most viewed products for last 30 days
    $products = Mage::getResourceModel('reports/product_collection')
        ->addAttributeToSelect('*')    
        ->setStoreId($storeId)
        ->addStoreFilter($storeId)
        ->addViewsCount()
        ->addViewsCount($from, $to)
        ->setPageSize($productCount);
    
    Mage::getSingleton('catalog/product_status')
            ->addVisibleFilterToCollection($products);
    Mage::getSingleton('catalog/product_visibility')
            ->addVisibleInCatalogFilterToCollection($products);
    
    return $products;
}

Hope this helps and thanks for reading.
- See more at: http://blog.chapagain.com.np/magento-how-to-get-most-viewed-products/#sthash.s6biTMMA.dpuf

Ways to Enable or Add Custom Breadcrumbs in Magento

There are some pages in Magento with no breadcrumbs enabled by default. In order to enable it, for example, on the checkout page, open checkout.xml file stored in 'layout' folder of the current theme, and find there 'checkout_onepage_index' block.  Then add to the block this code:
   
<reference name="breadcrumbs">
            <action method="addCrumb">
                <crumbName>Home</crumbName>
                <crumbInfo>
                    <label>Home</label>
                    <title>Home</title>
                    <link>/home</link>
                </crumbInfo>
            </action>
            <action method="addCrumb">
                <crumbName>Cart</crumbName>
                <crumbInfo>
                    <label>Cart</label>
                    <title>Cart</title>
                </crumbInfo>
            </action>
        </reference>

If the modified store is multilingual add into the opening tag of the block <translate="label">, here's the example:
   
< checkout_onepage_index translate="label">

The content of 'label' tag and proper translation should be added to mage_checkout.csv file.

The above described example illustrates how to show breadcrumbs with the help of xml, but it is possible to do it directly in the code of the phtml files. With the help of the line (see the example below) it is possible to enable breadcrumbs and show it on a certain page:
   
echo $this->getLayout()->getBlock('breadcrumbs')->toHtml();

This example describes a simple method how to add custom breadcrumbs:

// get breadcrumbs block
$breadcrumbs = $this->getLayout()->getBlock('breadcrumbs');
// add first item with link
$breadcrumbs->addCrumb(
'home',
 array(
'label'=>$this->__('Home'),
'title'=>$this->__('Home'),
'link'=>Mage::getBaseUrl()
)
);
// add second item without link
$breadcrumbs->addCrumb(
'brands',
 array(
'label'=>$this->__('Brands'),
'title'=>$this->__('Brands')
)
);
echo $breadcrumbs->toHtml();

The advantage of this method is that you can dynamically modify breadcrumbs (if it's necessary).

Creating Recursive Menu in Magento

In order to create the menu a function need to be added. The function that will receive the ID of the parent (main) categories as an argument and will be displaying child categories. Also the function should check presence of the sub-categories each time a child category is called. 

Here's the example of the 'recursive' function:
   
<?php
$rootСatId= Mage::app()->getStore()->getRootCategoryId();
$categories = Mage::getModel('catalog/category')->getCategories($rootСatId);
function  get_categories($categories) {
    $tree= '<ul>';
    foreach($categories as $category) {
        $cat = Mage::getModel('catalog/category')->load($category->getId());
        $tree .= '<li>'.
        '<a href="' . Mage::getUrl($cat->getUrlPath()). '">' .
            $category->getName() . "(" . $cat->getProductCount(). ")</a>\n";
        if($category->hasChildren()) {
            $children = Mage::getModel('catalog/category')->getCategories($category->getId());
             $tree .=  get_categories($children);
            }
         $tree .= '</li>';
    }
    return  $tree . '</ul>';
}
echo  get_categories($categories); ?>



To get the parent category ID and all its child categories, use this script:
   
$rootСatId= Mage::app()->getStore()->getRootCategoryId();
$categories = Mage::getModel('catalog/category')->getCategories($rootСatId);



In function: get_categories the list of the categories' links, the titles and products quantities in each of it, is formed.



Then the presence of the sub-categories should be checked. If there are some we should call function: get_categories with the current category ID as a parameter.
   
if($category->hasChildren()) {
$children = Mage::getModel('catalog/category')
->getCategories($category->getId());
$tree .=  get_categories($children);
     }

This circle could be repeated many times until the full list of the categories is formed.  And that's it.

Magento Layered Navigation in Drop-Down

Magento Layered Navigation in Drop-Down

It is very simple.
We just need to replace the contents of file
/app/design/frontend/default/your-magento-template/template/catalog/layer/filter.phtml
with

<select onchange="setLocation(this.value)">
  <option value=""><?php echo 'Choose an Option...' ?></option>
<?php foreach ($this->getItems() as $_item): ?>
    <option
        <?php if ($_item->getCount() > 0): ?>
        value="<?php echo $this->urlEscape($_item->getUrl()) ?>">
<?php echo $_item->getLabel() ?>
        <?php else: echo '>' . $_item->getLabel() ?>
        <?php endif; ?>
        (<?php echo $_item->getCount() ?>)
    </option>
<?php endforeach ?>
</select>

Magento : Category Flat Data index error

When reindexing "Category Flat Data " gives error
Cannot initialize the indexer process.
 I run the below query and the issue resolved.

ALTER TABLE catalog_category_entity ENGINE=INNODB;
ALTER TABLE core_store ENGINE=INNODB;
:)

Getting Configurable Product from Simple Product ID in Magento 1.5+

<?php
$simpleProductId = 465;
$parentIds = Mage::getResourceSingleton('catalog/product_type_configurable')
->getParentIdsByChild($simpleProductId);
$product = Mage::getModel('catalog/product')->load($parentIds[0]);
echo $product->getId(); // ID = 462 (aka, Parent of 465)
?>

Monday, August 26, 2013

Magento: Difference between order states and statuses

If you are building website in Magento, you may have noticed that there are two columns insales_flat_order table which are confusing. These are state and status. You might think what is the difference between these two, both having same meaning.
Well, this is not the case. They both are different. State is used by magento to tell if the order is new, processing, complete, holded, closed, canceled, etc.; while Statuses are the one that YOU would be defining at the backend in System -> Order Statuses. Magento displays order STATUSES and not STATES in the backend order detail page to let you know which status is assigned as per your mapping. Remember, multiple statuses can be mapped with one state, while vice versa is not possible.
Consider an example, your customer places an order as Cash on Delivery, you will need something like COD_Pending as the order status so that you know it is not yet paid. Magento will have state new for this, which makes you unpredictable of what kind of transaction is this, COD or Prepaid. The STATUS can be anything, as you define, for your understanding; while STATE is something which Magento needs to understand, internally.
In short, Magento uses order state internally for processing order, whereas order status are used by store owners to understand the exact order flow where one state can be assigned to multiple statuses.
To understand this in detail, have a look at this
Hope it helps!

Social media buttons

//linked in like button
http://developer.linkedin.com/plugins/share-button

//twitter tweet button
https://twitter.com/about/resources/buttons#tweet
https://dev.twitter.com/docs/tweet-button

//facebook like button
http://developers.facebook.com/docs/reference/plugins/like/

//google +1 button
http://www.google.com/intl/en/webmasters/+1/button/index.html

Magento : Add custom image attribute to category

Magento : Add custom image attribute to category

Just copy paste the below code in header.phtml and run yourmagento once, your attribute will be created and you can see in backend under manage category. After you are done remove this code again.

 ------------------------------------------------------------------------------------------
$setup = new Mage_Eav_Model_Entity_Setup('core_setup');

$setup->addAttribute('catalog_category', 'sliderimage', array(
    'group'         => 'General',
    'input'         => 'image',
    'type'          => 'varchar',
    'label'         => 'Slider Image',
    'backend'       => 'catalog/category_attribute_backend_image',
    'visible'       => 1,
    'required'        => 0,
    'user_defined' => 1,
    'global'        => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_GLOBAL,
));

Magento : Product list page wrong sorting by price

Magento : Product list page wrong sorting by price

When we install webtex_customergroupprice it has a bug when it sorts products

on product list page it is not correct. For this we need to change collections orderby.

We add

$collection->getSelect()->reset(Zend_Db_Select::ORDER)
->order('(min_price)'.$orderDir);

at the end of the function public function sortByPrice() in file "app/code/local/Webtex/Customer

GroupsPrice/Model/Observer.php".

Refresh Cache and the sorting is perfect.

Enjoy!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

Magento : Change page layout from controller

Just you need to replace one line of code in your controller
where you want to change the layout of the page if you are not
able to do from xml through setlayout.

Replace
$this->loadLayout();

with
$this->loadLayout()->getLayout()
->getBlock('root')->setTemplate('page/1column.phtml');

Magento : Change options of configurable product to radio button

Magento : Change options of configurable product to radio button

Replace the configurable.phtml code with below code:
<?php
$_product    = $this->getProduct();
$_attributes = Mage::helper('core')->decorateArray($this->getAllowAttributes());
?>
<?php if ($_product->isSaleable() && count($_attributes)):?>
    <dl>
    <?php foreach($_attributes as $_attribute): ?>
        <dt><label class="required"><em>*</em><?php echo $_attribute->getLabel() ?></label></dt>
        <dd<?php if ($_attribute->decoratedIsLast){?> class="last"<?php }?>>
            <div class="input-box">
                <select style="display:none;" name="super_attribute[<?php echo $_attribute->getAttributeId() ?>]"
id="attribute<?php echo $_attribute->getAttributeId() ?>"
 class="required-entry super-attribute-select">
                  
                  </select>
              </div>
        </dd>
    <?php endforeach; ?>
    </dl>
    <script type="text/javascript">
        var spConfig = new Product.Config(<?php echo $this->getJsonConfig() ?>);
    </script>
<?php endif;?>
<div id="r"></div>
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery("#attribute<?php echo $_attribute->getAttributeId() ?> option").each(function(i, e) {
    if(jQuery(this).val() == '')
    {}
    else
    {
    jQuery("<input type='radio' name='r' />")
        .attr("value", jQuery(this).val())
        .attr("checked", i == 0)
        .click(function () {
            jQuery("#attribute<?php echo $_attribute->getAttributeId() ?>").val(jQuery(this).val());
        })
        .appendTo("#r");
        jQuery("<span >&nbsp;&nbsp;&nbsp;"+jQuery(this).html()+"&nbsp;&nbsp;&nbsp;</span>")
        .appendTo("#r");
    }
      
});
});


</script>

Delete all products

TRUNCATE TABLE `catalog_product_bundle_option`;
TRUNCATE TABLE `catalog_product_bundle_option_value`;
TRUNCATE TABLE `catalog_product_bundle_selection`;
TRUNCATE TABLE `catalog_product_entity_datetime`;
TRUNCATE TABLE `catalog_product_entity_decimal`;
TRUNCATE TABLE `catalog_product_entity_gallery`;
TRUNCATE TABLE `catalog_product_entity_int`;
TRUNCATE TABLE `catalog_product_entity_media_gallery`;
TRUNCATE TABLE `catalog_product_entity_media_gallery_value`;
TRUNCATE TABLE `catalog_product_entity_text`;
TRUNCATE TABLE `catalog_product_entity_tier_price`;
TRUNCATE TABLE `catalog_product_entity_varchar`;
TRUNCATE TABLE `catalog_product_link`;
TRUNCATE TABLE `catalog_product_link_attribute_decimal`;
TRUNCATE TABLE `catalog_product_link_attribute_int`;
TRUNCATE TABLE `catalog_product_link_attribute_varchar`;
TRUNCATE TABLE `catalog_product_option`;
TRUNCATE TABLE `catalog_product_option_price`;
TRUNCATE TABLE `catalog_product_option_title`;
TRUNCATE TABLE `catalog_product_option_type_price`;
TRUNCATE TABLE `catalog_product_option_type_title`;
TRUNCATE TABLE `catalog_product_option_type_value`;
TRUNCATE TABLE `catalog_product_super_attribute`;
TRUNCATE TABLE `catalog_product_super_attribute_label`;
TRUNCATE TABLE `catalog_product_super_attribute_pricing`;
TRUNCATE TABLE `catalog_product_super_link`;
TRUNCATE TABLE `catalog_product_enabled_index`;
TRUNCATE TABLE `catalog_product_website`;
TRUNCATE TABLE `catalog_product_entity`;
TRUNCATE TABLE `cataloginventory_stock_item`;
TRUNCATE TABLE `cataloginventory_stock_status`;

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);
?>

Sunday, August 25, 2013

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
*/
?>

Get Magento Urls in Phtml Page

Get Base Url :
Mage::getBaseUrl();
Get Store Url : 
Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB);
Get Skin Url :
Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_SKIN);
$this->getSkinUrl(‘images/imagename.jpg’);
Get Media Url :
Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA);
Get Js Url : 
Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_JS);
Get Current Url
Mage::helper(‘core/url’)->getCurrentUrl();
Get Home Url
Mage::helper(‘core/url’)->getHomeUrl();

Changing the Admin URL

Open up the /app/etc/local.xml file, locate the <frontName> tag, and change the ‘admin’ part it to something a lot more random, eg:

<frontName><![CDATA[supersecret-admin-name]]></frontName>

Clear your cache and sessions.

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;
?>

Is product purchasable?

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

Run Magento Code Externally

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

Get Simple Products of a Configurable Product

<?php
if($_product->getTypeId() == "configurable") {
$ids = $_product->getTypeInstance()->getUsedProductIds();
?>
<ul>
<?php
foreach ($ids as $id) {
$simpleproduct = Mage::getModel('catalog/product')
->load($id);
?>
<li>
<?php
echo $simpleproduct->getName() . " - " .
(int)Mage::getModel('cataloginventory/stock_item')
->
loadByProduct($simpleproduct)->getQty();
?>
</li>
<?php
}
?>
</ul>
<?php
}
?>

Saturday, August 24, 2013

Create Catalog Price Rule Programmatically in Magento

Here, you will see how to create Catalog Price Rule in Magento through code.

Catalog Rules are applied on products before they are added to the cart.

To create a Catalog Price Rule from Admin Panel, we go to Promotions -> Catalog Price Rules and select Add New Rule.

Basically, there are three main parts for Catalog Price Rule, i.e. Rule Information, Conditions, and Actions.

Here is the code to create Catalog Price Rule. In this code example, I have created Catalog Price Rule with the following information:-

- The rule is applied to particular product with the particular SKU (in our case: ‘chair’)
- The rule is applied as Fixed Amount Discount To certain amount (in our case: 20) of currency amount

$name = "My Catalog Price Rule"; // name of Catalog Price Rule
$websiteId = 1;
$customerGroupId = 2;
$actionType = 'to_fixed'; // discount to fixed amount
//(other options are: by_fixed, by_percent, to_percent)
$discount = 20; // discount amount
$sku = 'chair'; // product sku

$catalogPriceRule = Mage::getModel('catalogrule/rule');

$catalogPriceRule->setName($name)
                 ->setDescription('')
                 ->setIsActive(1)
                 ->setWebsiteIds(array($websiteId))
                 ->setCustomerGroupIds(array($customerGroupId))
                 ->setFromDate('')
                 ->setToDate('')
                 ->setSortOrder('')
                 ->setSimpleAction($actionType)
                 ->setDiscountAmount($discount)
                 ->setStopRulesProcessing(0);

$skuCondition = Mage::getModel('catalogrule/rule_condition_product')
                    ->setType('catalogrule/rule_condition_product')
                    ->setAttribute('sku')
                    ->setOperator('==')
                    ->setValue($sku);

try {
    $catalogPriceRule->getConditions()->addCondition($skuCondition);
    $catalogPriceRule->save();
    $catalogPriceRule->applyAll();
} catch (Exception $e) {
    Mage::getSingleton('core/session')->addError(Mage::helper('catalog')
->__($e->getMessage()));
    return;
}

A new Catalog Price Rule with the name “My Catalog Price Rule” has been created. You can view the rule from Promotions -> Catalog Price Rules in admin.

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);
}
?>

Get associated products

In /app/design/frontend/default/site/template/catalog/product/view/type/

<?php $_helper = $this->helper('catalog/output'); ?>
<?php $_associatedProducts = $this->getAllowProducts() ?>
<?php //var_dump($_associatedProducts); ?>
<br />
<br />
<?php if (count($_associatedProducts)): ?>
    <?php foreach ($_associatedProducts as $_item): ?>
        <a href="<?php echo $_item->getProductUrl() ?>"><?php echo $_helper->productAttribute($_item, $_item->getName(), 'name') ?> |
<?php echo $_item->getName() ?> |
<?php echo $_item->getPrice() ?></a>
        <br />
        <br />
    <?php endforeach; ?>
<?php endif; ?>

Get the current category/product/cms page

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

How to delete a quote in Magento

Use the code below to delete a quote:


<?php
$quoteID = Mage::getSingleton("checkout/session")
->getQuote()->getId();

if($quoteID)
{
try {
$quote = Mage::getModel("sales/quote")->load($quoteID);
$quote->setIsActive(false);
$quote->delete();

return "cart deleted";
} catch(Exception $e) {
return $e->getMessage();
}
}else{
return "no quote found";
}

Cart Data

<?php
$cart = Mage::getModel('checkout/cart')->getQuote()->getData();
print_r($cart);
$cart = Mage::helper('checkout/cart')->getCart()->getItemsCount();
print_r($cart);
$session = Mage::getSingleton('checkout/session');
foreach ($session->getQuote()->getAllItems() as $item) {
echo $item->getName();
Zend_Debug::dump($item->debug());
}
?>

Friday, August 23, 2013

Turn template hints on/off via database

UPDATE
`core_config_data`
SET
`value` = 0
WHERE
`path` = "dev/debug/template_hints"
OR
`path` = "dev/debug/template_hints_blocks";

How to get shipping and handling cost, tax, discount in magento on shopping cart page

We can simply use the following code
// To get the shipping and handling charge on shopping cart page
Mage::getSingleton('checkout/session')->getQuote()->getShippingAddress()->getShippingAmount();
 // To get discount and tax  on shopping cart page
$totals = Mage::getSingleton('checkout/session')->getQuote()->getTotals(); //Total object
 // To get the discount
if(isset($totals['discount']) && $totals['discount']->getValue()) {
echo 'Discount :'. $discount = $totals['discount']->getValue(); //Discount value if applied
} else {
$discount = '';
}
 // To get tax
if(isset($totals['tax']) && $totals['tax']->getValue()) {
echo 'Tax :'.$tax = $totals['tax']->getValue(); //Tax value if present
} else {
$tax = '';
}

How to Override controller in magento / Override controller’s action in magento

Requirement : Some times you may run into situation where you want to override the core functionality of Magento core controllers. So in this case, The best practise is override the controller then override actions or add new actions for custom requirement.

For example you want to override OnepageController.php file and overwride indexAction.

In this example my custom module name space is “MyBlog” and i am going to overwride indexAction Mage_Checkout_OnepageController

Base File Path : app/code/core/Mage/Checkout/controllers/OnepageController.php

To Do the same we have to follow bellow steps.

Step1: We need to create a custom module

File Path : app/etc/modules/

File Name: MyBlog_Checkout.xml

File Content:

<?xml version="1.0"?>
<config>
    <modules>
        <MyBlog_Checkout>
            <active>true</active>
            <codePool>local</codePool>
        </MyBlog_Checkout>
    </modules>
</config>

Step2: Now we have to create bellow files in our custom module

File Path: app/code/local/MyBlog/Checkout/etc/config.xml

Bellow is content for config.xml file

<?xml version="1.0"?>
<config>
     <modules>
       <MyBlog_Checkout>
         <version>0.0.1</version>
       </MyBlog_Checkout>
     </modules>

    <frontend>
        <routers>
            <checkout>
                <args>
                    <modules>
                        <MyBlog_Checkout before="Mage_Checkout">MyBlog_Checkout</MyBlog_Checkout>
                    </modules>
                </args>
            </checkout>
        </routers>
    </frontend>
</config>

Bellow is content for OnepageController.php

File Path : app/code/local/MyBlog/Checkout/controllers/OnepageController.php

<?php

require_once 'Mage/Checkout/controllers/OnepageController.php';
class MyBlog_Checkout_OnepageController extends Mage_Checkout_OnepageController {

     public function indexAction()
    {
        echo "Great! You are in MyBlog checkout controller section";
        exit;
    }

}
?>

How to Add related products in Magento by code / script

To create the related product programmatically in Magento

<?php
set_time_limit(0);
ini_set(‘memory_limit’,’1024M’);
require_once ‘../../app/Mage.php’;
Mage::app();

$sku=’12345’;  //some Sku
$product = Mage::getModel(‘catalog/product’)->loadByAttribute(‘sku’,$sku);

if($product){
$sRelatedProducts = "123456,123";
$aRelatedProducts = explode(‘,’, $sRelatedProducts);  // or other way to get the array of related product sku

$aParams = array();
$nRelatedCounter = 1;
$aProduct    = Mage::getModel(‘catalog/product’)->loadByAttribute(‘sku’, $sku);
$aMainProduct = Mage::getModel(‘catalog/product’);
$aMainProduct->load($aProduct['entity_id']);

foreach($aRelatedProducts as $sSku)
{
$aRelatedProduct = Mage::getModel(‘catalog/product’)->loadByAttribute(‘sku’, $sSku);

$aParams[$aRelatedProduct['entity_id']] = array(
‘position’     => $nRelatedCounter
);

$nRelatedCounter++;
}

$product->setRelatedLinkData($aParams);
$product->save();
}

echo “Great!!”;

?>

How to call category list in footer in magento

<?php $helper = $this->helper('catalog/category') ?>

<?php foreach ($helper->getStoreCategories() as $_category): ?>
<a href="<?php echo Mage::getModel('catalog/category')                                                                                                                                                                                                                                                                                            ->setData($_category->getData())->getUrl(); ?>" title="<?php echo $_category->getName() ?>">   <?php echo $_category->getName() ?></a>
<?php endforeach ?>

Create a Country Drop Down in the Magento Admin

<?php
$fieldset->addField('country', 'select', array(
'name' => 'country',
'label' => 'Country',
'values' => Mage::getModel
(
'adminhtml/system_config_source_country')
->toOptionArray(),
));
?>

Get An Array of Country Names/Codes in Magento

<?php
$countryList = Mage::getResourceModel 
                ('directory/country_collection')
->loadData()
->toOptionArray(false);

echo '<pre>';
print_r( $countryList);
exit('</pre>');
?>

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; ?>

Category Navigation Listings in Magento

<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>

Debug using zend

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

$_GET, $_POST & $_REQUEST Variables

<?php
// $_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: Mass Exclude/Unexclude Images

# 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';

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 The Current URL In Magento

<?php echo Mage::helper('core/url')->getCurrentUrl(); ?>

Check if customer is logged in

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

how to add/update category in magento from csv programmatically

<?php
set_time_limit(0);
ini_set(‘memory_limit’,’1024M’);
require_once ‘../../app/Mage.php’;
Mage::app();

//read data from csv file
$row = 1; $cat_arr = array();
if (($handle = fopen(“category.csv”, “r”)) !== FALSE)
{
while (($data = fgetcsv($handle, 100000, “,”)) !== FALSE)
{
if($row > 1)
{

/* $data[0] is csv column in csv file
$data[1],$data[2],$data[3],$data[4] is category Id column */

$cat_arr[trim($data[0])] = $data[1].”,”.$data[2].”,”.$data[3].”,”.$data[4].”,”.$data[5].”,”.$data[6].”,”.$data[7]; // $data[0] column represent sku

}

$row++;
}
fclose($handle);
}

$products = Mage::getResourceModel(‘catalog/product_collection’);
$i = 1 ;
foreach ( $products as $index => $productModel )
{
$_product = Mage::getModel(‘catalog/product’)->load($productModel->getId());
$cnids = $cat_arr[$_product->getSku()];
$ids = explode(“,”,$cnids);
$_product->setCategoryIds($ids);
$_product->save();
$i++;
}

?>

Get Configurable product's Children's (simple product) custom attributes

<?php
// input is $_product and result is iterating child products
$conf = Mage::getModel('catalog/product_type_configurable')
->setProduct($_product);
$col = $conf->getUsedProductCollection()
->addAttributeToSelect('*')->addFilterByRequiredOptions();
foreach($col as $simple_product){
var_dump($simple_product->getId());
}
?>

Load category by id

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

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');
?>

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;
}
?>

Update all subscribers into a customer group (e.g. 5)

UPDATE
customer_entity,
newsletter_subscriber
SET
customer_entity.`group_id` = 5
WHERE
customer_entity.`entity_id` = newsletter_subscriber.`customer_id`
AND
newsletter_subscriber.`subscriber_status` = 1;

Including jquery to magento

First step is to include j query to your magento website.To achieve this just add a new line add js to your page.xml layout or you can include js in template/page/html/head.phtml .

After this just include jquery.noConfilct to remove conflict between prototype.js and jquery library
For this use following  snippet

var $j = jQuery.noConflict(); 

$j
(document).ready(function(){
    //here you can add your jquery code and jquery
 $ is to be replaced with $j 
   as it is the new replaced variable 
for the jquery script
});

Magento Enable template path hint

To enable magento path hint for your magento website first login into your admin section i.e magento backend now go to System->Configuration->Developer
Inside this you have to Debug option.If the Current Configuration Scope is Default you will be not able to set template path hints for your magento website So change to you website after this change Template Path Hints to yes.

Your Template path hint has been enabled after this you can view template path hint on the frontend of your website if some how due to cache you are not getting the path hint so go to System Cache management flush or refresh the cache are you are ready to go.

Magento new feature for Category manager

Magento 1.5 has come up with anew feature for categories and made category design management a lot more easier now when you click on a category and apply a custom or a new design for a particular category you can extend that design for its sub categories and products by just selecting the use parent category settings and apply to products.

Magento Tutorial : Adding a product

Steps to Follow to add new Product:-
1)      First login into Magento admin section 

2) Now from top menu go to Catalog->Manage Product.

3) To add new Product click on the button Add Product .

4) First Product Setting Page is prompted Now select Attribute Type as Default and and Product type as Simple Product.

5) After proceeding further you will be redirected to Product information page  in the General tab Provide the details
i.e
 Name :- Product Name
SKU :- Unique Sku number product
Weight :- Product weight
Status :- Enable to activate the product
Tax Class:-According to the product 
Visiblity :- Whether product is searchable from web site  default is [catalog/search]
Brands: Select From Drop Down

6)  After that go to price section here provide Price which is required
    Beside this you can also provide cost and
Tier price  which is buy 2 for
Special price for sale price special price you offer in your store

7)In Meta section we can provide meta data about product to make your store seo friendly

8)In Image section We can upload images of product from our local file system and assign distinguished image for small image thumbnail and base image

9)In description section We provide description about the Product which will displayed on the frontend of product view page.

10)Now Go to Inventory Section Provide Details about product stock the qty(availability of product ) and set
Stock Availability:in Stock  if the stock availability is set to out of stock the product will not be available on frontend

11)In Website Section Check the website in which the product will be available now we have only one website we can check  main website to true i.e our website will be available to our main website.

12)After This Click on Categories tab to assign category to the product

 13) To assign Best Suitable Products to a product go to Up-sells tab Search the best suitable product from the grid now assign the product  which suits best with this product.

14)After that we can also provide custom option to the product  For this we have assign size custom option for the jeans we can go to custom options add a new option from custom option assign its Title as size now will also assign its type i.e drop down radio button or check-box we can assign different price list for different  product options.

Magento Code to get Store Information

Most of the time we want to access Store Contact info at different places of our magento site to do this we have a very simple and useful code i.e
<?php echo Mage::getStoreConfig('general/store_information');    ?>

This code will fetch you an array containing complete store which is provided at backend From System->Configuration->General->Store Information.

If do not Want the complete array or just want to use address info use

<?php echo Mage::getStoreConfig('general/store_information/address');    ?>

In similar fashion for store phone number use this code

<?php echo Mage::getStoreConfig('general/store_information/phone'); ?>  

Magento go Detailed report

Magento go is advnce version of software as a service(SaaS) it is a platform as a service (Paas)

Magento is a combined structure of  Community professional and enterprise edition .In magento go

 a well structured centralized database is there to provide you business logic of  your magento store. It
is more over a advance hosting service for your magento web store.There are similar webs shop like magento go are BigCommerce and shopify.

Magento Google Checkout

Go System->Configuration->Google API->Google Checkout
Enable Google Checkout and other configurations set details about your google checkout like merchant id, merchant key etc. Save the configuration.
You Can Go to google checkout sandbox testing platform and can easily test about google checkout 
you need to have a seller merchant account and buy account to test it both of this account can be created from   google checkout sandbox just provide sample or proxy data of the users and after this you are ready to test your google checkout integrated with magento  on the sandbox platform with no real money transfer but it will stimulate the exact scenario after test you can make it live but changing the configuration to live from backend.

PHP regular expressions examples

Mastering Regular Expressions quickly covers the basics of regular-expression syntax, then delves into the mechanics of expression-processing, common pitfalls, performance issues, and implementation-specific differences. Written in an engaging style and sprinkled with solutions to complex real-world problems, MRE offers a wealth information that you use. I will start with some simple usage examples of the regular expressions and continue with a huge list of cases for various situations where we would normally need a regex to operate. We will use simple functions which return TRUE or FALSE. $regex will serve as our regular expression to match against and $text will be our text (pretty obvious):

function do_reg($text, $regex)
{
    if (preg_match($regex, $text)) {
        return TRUE;
    }
    else {
        return FALSE;
    }
}

The next function will get the part of a given string ($text) matched by the regex ($regex) using a group srorage ($regs). By changing the $regs[0] to $regs[1] we can use a capturing group (in this case griup 1) to match against. The capturing group can also have a name ($regs['groupname']):

function do_reg($text, $regex, $regs)
{
    if (preg_match($regex, $text, $regs)) {
        $result = $regs[0];
    }
    else {
        $result = "";
    }
    return $result;
}

The following function will return an array of all regex matches in a given string ($text):

function do_reg($text, $regex)
{
    preg_match_all($regex, $text, $result, PREG_PATTERN_ORDER);
    return $result = $result[0];
}

Next we can iterate (loop) over all matches in a string ($text) and output the results:

function do_reg($text, $regex)
{
    preg_match_all($regex, $text, $result, PREG_PATTERN_ORDER);
    for ($i = 0; $i < count($result[0]); $i++) {
    $result[0][$i];
}
}

Extending the above one we can iterate over all matches ($text) and capture groups in a string ($text):

function do_reg($text, $regex)
{
    preg_match_all($regex, $text, $result, PREG_SET_ORDER);
    for ($matchi = 0; $matchi < count($result); $matchi++) {
        for ($backrefi = 0; $backrefi < count($result[$matchi]); $backrefi++) {
            $result[$matchi][$backrefi];
        }
    }
}
}

REGULAR EXPRESSION EXAMPLES BY SITUATIONS AND NEEDS: Addresses

//Address: State code (US)
'/\\b(?:A[KLRZ]|C[AOT]|D[CE]|FL|GA|HI|I[ADLN]
|K[SY]|LA|M[ADEINOST]|N[CDEHJMVY]|O[HKR]|PA|RI|S[CD]|T[NX]
|UT|V[AT]|W[AIVY])\\b/'

//Address: ZIP code (US)
'\b[0-9]{5}(?:-[0-9]{4})?\b'

Columns

//Columns: Match a regex starting at a specific column on a line.
'^.{%SKIPAMOUNT%}(%REGEX%)'

//Columns: Range of characters on a line, captured into backreference 1
//Iterate over all matches to extract a column of text from a file
//E.g. to grab the characters in colums 8..10, set SKIPAMOUNT to 7, and CAPTUREAMOUNT to 3
'^.{%SKIPAMOUNT%}(.{%CAPTUREAMOUNT%})'

Credit cards

//Credit card: All major cards
'^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6011[0-9]{12}|3(?:0[0-5]|[68][0-9])[0-9]{11}|3[47][0-9]{13})$'

//Credit card: American Express
'^3[47][0-9]{13}$'

//Credit card: Diners Club
'^3(?:0[0-5]|[68][0-9])[0-9]{11}$'

//Credit card: Discover
'^6011[0-9]{12}$'

//Credit card: MasterCard
'^5[1-5][0-9]{14}$'

//Credit card: Visa
'^4[0-9]{12}(?:[0-9]{3})?$'

//Credit card: remove non-digits
'/[^0-9]+/'

CSV

//CSV: Change delimiter
//Changes the delimiter from a comma into a tab.
//The capturing group makes sure delimiters inside double-quoted entries are ignored.
'("[^"\r\n]*")?,(?![^",\r\n]*"$)'

//CSV: Complete row, all fields.
//Match complete rows in a comma-delimited file that has 3 fields per row,
//capturing each field into a backreference. 
//To match CSV rows with more or fewer fields, simply duplicate or delete the capturing groups.
'^("[^"\r\n]*"|[^,\r\n]*),("[^"\r\n]*"|[^,\r\n]*),("[^"\r\n]*"|[^,\r\n]*)$'

//CSV: Complete row, certain fields.
//Set %SKIPLEAD% to the number of fields you want to skip at the start, and %SKIPTRAIL% to
//the number of fields you want to ignore at the end of each row. 
//This regex captures 3 fields into backreferences.  To capture more or fewer fields,
//simply duplicate or delete the capturing groups.
'^(?:(?:"[^"\r\n]*"|[^,\r\n]*),){%SKIPLEAD%}("[^"\r\n]*"|[^,\r\n]*),("[^"\r\n]*"|[^,\r\n]*),("[^"\r\n]*"|[^,\r\n]*)(?:(?:"[^"\r\n]*"|[^,\r\n]*),){%SKIPTRAIL%}$'

//CSV: Partial row, certain fields
//Match the first SKIPLEAD+3 fields of each rows in a comma-delimited file that has SKIPLEAD+3
//or more fields per row.  The 3 fields after SKIPLEAD are each captured into a backreference. 
//All other fields are ignored.  Rows that have less than SKIPLEAD+3 fields are skipped. 
//To capture more or fewer fields, simply duplicate or delete the capturing groups.
'^(?:(?:"[^"\r\n]*"|[^,\r\n]*),){%SKIPLEAD%}("[^"\r\n]*"|[^,\r\n]*),("[^"\r\n]*"|[^,\r\n]*),("[^"\r\n]*"|[^,\r\n]*)'

//CSV: Partial row, leading fields
//Match the first 3 fields of each rows in a comma-delimited file that has 3 or more fields per row. 
//The first 3 fields are each captured into a backreference.  All other fields are ignored. 
//Rows that have less than 3 fields are skipped.  To capture more or fewer fields,
//simply duplicate or delete the capturing groups.
'^("[^"\r\n]*"|[^,\r\n]*),("[^"\r\n]*"|[^,\r\n]*),("[^"\r\n]*"|[^,\r\n]*)'

//CSV: Partial row, variable leading fields
//Match the first 3 fields of each rows in a comma-delimited file. 
//The first 3 fields are each captured into a backreference.
//All other fields are ignored.  If a row has fewer than 3 field, some of the backreferences
//will remain empty.  To capture more or fewer fields, simply duplicate or delete the capturing groups. 
//The question mark after each group makes that group optional.
'^("[^"\r\n]*"|[^,\r\n]*),("[^"\r\n]*"|[^,\r\n]*)?,("[^"\r\n]*"|[^,\r\n]*)?'

Dates

//Date d/m/yy and dd/mm/yyyy
//1/1/00 through 31/12/99 and 01/01/1900 through 31/12/2099
//Matches invalid dates such as February 31st
'\b(0?[1-9]|[12][0-9]|3[01])[- /.](0?[1-9]|1[012])[- /.](19|20)?[0-9]{2}\b'

//Date dd/mm/yyyy
//01/01/1900 through 31/12/2099
//Matches invalid dates such as February 31st
'(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)[0-9]{2}'

//Date m/d/y and mm/dd/yyyy
//1/1/99 through 12/31/99 and 01/01/1900 through 12/31/2099
//Matches invalid dates such as February 31st
//Accepts dashes, spaces, forward slashes and dots as date separators
'\b(0?[1-9]|1[012])[- /.](0?[1-9]|[12][0-9]|3[01])[- /.](19|20)?[0-9]{2}\b'

//Date mm/dd/yyyy
//01/01/1900 through 12/31/2099
//Matches invalid dates such as February 31st
'(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)[0-9]{2}'

//Date yy-m-d or yyyy-mm-dd
//00-1-1 through 99-12-31 and 1900-01-01 through 2099-12-31
//Matches invalid dates such as February 31st
'\b(19|20)?[0-9]{2}[- /.](0?[1-9]|1[012])[- /.](0?[1-9]|[12][0-9]|3[01])\b'

//Date yyyy-mm-dd
//1900-01-01 through 2099-12-31
//Matches invalid dates such as February 31st
'(19|20)[0-9]{2}[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])'

Delimiters

//Delimiters: Replace commas with tabs
//Replaces commas with tabs, except for commas inside double-quoted strings
'((?:"[^",]*+")|[^,]++)*+,'

Email addresses

//Email address
//Use this version to seek out email addresses in random documents and texts.
//Does not match email addresses using an IP address instead of a domain name.
//Does not match email addresses on new-fangled top-level domains with more than 4 letters such as .museum. 
//Including these increases the risk of false positives when applying the regex to random documents.
'\b[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b'

//Email address (anchored)
//Use this anchored version to check if a valid email address was entered.
//Does not match email addresses using an IP address instead of a domain name.
//Does not match email addresses on new-fangled top-level domains with more than 4 letters such as .museum.
//Requires the "case insensitive" option to be ON.
'^[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$'

//Email address (anchored; no consecutive dots)
//Use this anchored version to check if a valid email address was entered.
//Improves on the original email address regex by excluding addresses with consecutive dots such as john@aol...com
//Does not match email addresses using an IP address instead of a domain name.
//Does not match email addresses on new-fangled top-level domains with more than 4 letters such as .museum. 
//Including these increases the risk of false positives when applying the regex to random documents.
'^[A-Z0-9._%-]+@(?:[A-Z0-9-]+\.)+[A-Z]{2,4}$'

//Email address (no consecutive dots)
//Use this version to seek out email addresses in random documents and texts.
//Improves on the original email address regex by excluding addresses with consecutive dots such as john@aol...com
//Does not match email addresses using an IP address instead of a domain name.
//Does not match email addresses on new-fangled top-level domains with more than 4 letters such as .museum. 
//Including these increases the risk of false positives when applying the regex to random documents.
'\b[A-Z0-9._%-]+@(?:[A-Z0-9-]+\.)+[A-Z]{2,4}\b'

//Email address (specific TLDs)
//Does not match email addresses using an IP address instead of a domain name.
//Matches all country code top level domains, and specific common top level domains.
'^[A-Z0-9._%-]+@[A-Z0-9.-]+\.(?:[A-Z]{2}|com|org|net|biz|info|name|aero|biz|info|jobs|museum|name)$'

//Email address: Replace with HTML link
'\b(?:mailto:)?([A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4})\b'

HTML

//HTML comment
'<!--.*?-->'

//HTML file
//Matches a complete HTML file.  Place round brackets around the .*? parts you want to extract from the file.
//Performance will be terrible on HTML files that miss some of the tags
//(and thus won't be matched by this regular expression).  Use the atomic version instead when your search
//includes such files (the atomic version will also fail invalid files, but much faster).
'<html>.*?<head>.*?<title>.*?</title>.*?</head>.*?<body[^>]*>.*?</body>.*?</html>'

//HTML file (atomic)
//Matches a complete HTML file.  Place round brackets around the .*? parts you want to extract from the file.
//Atomic grouping maintains the regular expression's performance on invalid HTML files.
'<html>(?>.*?<head>)(?>.*?<title>)(?>.*?</title>)(?>.*?</head>)(?>.*?<body[^>]*>)(?>.*?</body>).*?</html>'

//HTML tag
//Matches the opening and closing pair of whichever HTML tag comes next.
//The name of the tag is stored into the first capturing group.
//The text between the tags is stored into the second capturing group.
'<([A-Z][A-Z0-9]*)[^>]*>(.*?)</\1>'

//HTML tag
//Matches the opening and closing pair of a specific HTML tag.
//Anything between the tags is stored into the first capturing group.
//Does NOT properly match tags nested inside themselves.
'<%TAG%[^>]*>(.*?)</%TAG%>'

//HTML tag
//Matches any opening or closing HTML tag, without its contents.
'</?[a-z][a-z0-9]*[^<>]*>'



IP addresses

//IP address
//Matches 0.0.0.0 through 999.999.999.999
//Use this fast and simple regex if you know the data does not contain invalid IP addresses.
'\b([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\b'

//IP address
//Matches 0.0.0.0 through 999.999.999.999
//Use this fast and simple regex if you know the data does not contain invalid IP addresses,
//and you don't need access to the individual IP numbers.
'\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b'

//IP address
//Matches 0.0.0.0 through 255.255.255.255
//Use this regex to match IP numbers with accurracy, without access to the individual IP numbers.
'\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b'

//IP address
//Matches 0.0.0.0 through 255.255.255.255
//Use this regex to match IP numbers with accurracy.
//Each of the 4 numbers is stored into a capturing group, so you can access them for further processing.
'\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b'

Lines

//Lines: Absolutely blank (no whitespace)
//Regex match does not include line break after the line.
'^$'

//Lines: Blank (may contain whitespace)
//Regex match does not include line break after the line.
'^[ \t]*$'

//Lines: Delete absolutely blank lines
//Regex match includes line break after the line.
'^\r?\n'

//Lines: Delete blank lines
//Regex match includes line break after the line.
'^[ \t]*$\r?\n'

//Lines: Delete duplicate lines
//This regex matches two or more lines, each identical to the first line. 
//It deletes all of them, except the first.
'^(.*)(\r?\n\1)+$'

//Lines: Truncate a line after a regex match.
//The regex you specify is guaranteed to match only once on each line. 
//If the original regex you specified should match more than once,
//the line will be truncated after the last match.
preg_replace('^.*(%REGEX%)(.*)$', '$1$2', $text);

//Lines: Truncate a line before a regex match.
//If the regex matches more than once on the same line, everything before the last match is deleted.
preg_replace('^.*(%REGEX%)', '$1', $text);

//Lines: Truncate a line before and after a regex match.
//This will delete everything from the line not matched by the regular expression.
preg_replace('^.*(%REGEX%).*$', '$1', $text);

Logs

//Logs: Apache web server
//Successful hits to HTML files only.  Useful for counting the number of page views.
'^((?#client IP or domain name)\S+)\s+((?#basic authentication)\S+\s+\S+)\s+\[((?#date and time)[^]]+)\]\s+"(?:GET|POST|HEAD) ((?#file)/[^ ?"]+?\.html?)\??((?#parameters)[^ ?"]+)? HTTP/[0-9.]+"\s+(?#status code)200\s+((?#bytes transferred)[-0-9]+)\s+"((?#referrer)[^"]*)"\s+"((?#user agent)[^"]*)"$'

//Logs: Apache web server
//404 errors only
'^((?#client IP or domain name)\S+)\s+((?#basic authentication)\S+\s+\S+)\s+\[((?#date and time)[^]]+)\]\s+"(?:GET|POST|HEAD) ((?#file)[^ ?"]+)\??((?#parameters)[^ ?"]+)? HTTP/[0-9.]+"\s+(?#status code)404\s+((?#bytes transferred)[-0-9]+)\s+"((?#referrer)[^"]*)"\s+"((?#user agent)[^"]*)"$'

Numbers

//Number: Currency amount
//Optional thousands separators; optional two-digit fraction
'\b[0-9]{1,3}(?:,?[0-9]{3})*(?:\.[0-9]{2})?\b'

//Number: Currency amount
//Optional thousands separators; mandatory two-digit fraction
'\b[0-9]{1,3}(?:,?[0-9]{3})*\.[0-9]{2}\b'

//Number: floating point
//Matches an integer or a floating point number with mandatory integer part.  The sign is optional.
'[-+]?\b[0-9]+(\.[0-9]+)?\b'

//Number: floating point
//Matches an integer or a floating point number with optional integer part.  The sign is optional.
'[-+]?\b[0-9]*\.?[0-9]+\b'

//Number: hexadecimal (C-style)
'\b0[xX][0-9a-fA-F]+\b'

//Number: Insert thousands separators
//Replaces 123456789.00 with 123,456,789.00
'(?<=[0-9])(?=(?:[0-9]{3})+(?![0-9]))'

//Number: integer
//Will match 123 and 456 as separate integer numbers in 123.456
'\b\d+\b'

//Number: integer
//Does not match numbers like 123.456
'(?<!\S)\d++(?!\S)'

//Number: integer with optional sign
'[-+]?\b\d+\b'

//Number: scientific floating point
//Matches an integer or a floating point number.
//Integer and fractional parts are both optional.
'[-+]?(?:\b[0-9]+(?:\.[0-9]*)?|\.[0-9]+\b)(?:[eE][-+]?[0-9]+\b)?'

//Number: scientific floating point
//Matches an integer or a floating point number with optional integer part.
//Both the sign and exponent are optional.
'[-+]?\b[0-9]*\.?[0-9]+(?:[eE][-+]?[0-9]+)?\b'

Passwords

//Password complexity
//Tests if the input consists of 6 or more letters, digits, underscores and hyphens.
//The input must contain at least one upper case letter, one lower case letter and one digit.
'\A(?=[-_a-zA-Z0-9]*?[A-Z])(?=[-_a-zA-Z0-9]*?[a-z])(?=[-_a-zA-Z0-9]*?[0-9])[-_a-zA-Z0-9]{6,}\z'

//Password complexity
//Tests if the input consists of 6 or more characters.
//The input must contain at least one upper case letter, one lower case letter and one digit.
'\A(?=[-_a-zA-Z0-9]*?[A-Z])(?=[-_a-zA-Z0-9]*?[a-z])(?=[-_a-zA-Z0-9]*?[0-9])\S{6,}\z'

File paths

//Path: Windows
'\b[a-z]:\\[^/:*?"<>|\r\n]*'

//Path: Windows
//Different elements of the path are captured into backreferences.
'\b((?#drive)[a-z]):\\((?#folder)[^/:*?"<>|\r\n]*\\)?((?#file)[^\\/:*?"<>|\r\n]*)'

//Path: Windows or UNC
'(?:(?#drive)\b[a-z]:|\\\\[a-z0-9]+)\\[^/:*?"<>|\r\n]*'

//Path: Windows or UNC
//Different elements of the path are captured into backreferences.
'((?#drive)\b[a-z]:|\\\\[a-z0-9]+)\\((?#folder)[^/:*?"<>|\r\n]*\\)?((?#file)[^\\/:*?"<>|\r\n]*)'

Phone numbers

//Phone Number (North America)
//Matches 3334445555, 333.444.5555, 333-444-5555, 333 444 5555, (333) 444 5555 and all combinations thereof.
//Replaces all those with (333) 444-5555
preg_replace('\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})', '(\1) \2-\3', $text);

//Phone Number (North America)
//Matches 3334445555, 333.444.5555, 333-444-5555, 333 444 5555, (333) 444 5555 and all combinations thereof.
'\(?[0-9]{3}\)?[-. ]?[0-9]{3}[-. ]?[0-9]{4}'

Postal codes

//Postal code (Canada)
'\b[ABCEGHJKLMNPRSTVXY][0-9][A-Z] [0-9][A-Z][0-9]\b'

//Postal code (UK)
'\b[A-Z]{1,2}[0-9][A-Z0-9]? [0-9][ABD-HJLNP-UW-Z]{2}\b'

Programming

//Programming: # comment
//Single-line comment started by # anywhere on the line
'#.*$'

//Programming: # preprocessor statement
//Started by # at the start of the line, possibly preceded by some whitespace.
'^\s*#.*$'

//Programming: /* comment */
//Does not match nested comments.  Most languages, including C, Java, C#, etc.
//do not allow comments to be nested.  I.e. the first */ closes the comment.
'/\*.*?\*/'

//Programming: // comment
//Single-line comment started by // anywhere on the line
'//.*$'

//Programming: GUID
//Microsoft-style GUID, numbers only.
'[A-Z0-9]{8}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{12}'

//Programming: GUID
//Microsoft-style GUID, with optional parentheses or braces.
//(Long version, if your regex flavor doesn't support conditionals.)
'[A-Z0-9]{8}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{12}|\([A-Z0-9]{8}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{12}\)|\{[A-Z0-9]{8}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{12}\}'

//Programming: GUID
//Microsoft-style GUID, with optional parentheses or braces.
//Short version, illustrating the use of regex conditionals.  Not all regex flavors support conditionals. 
//Also, when applied to large chunks of data, the regex using conditionals will likely be slower
//than the long version.  Straight alternation is much easier to optimize for a regex engine.
'(?:(\()|(\{))?[A-Z0-9]{8}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{12}(?(1)\))(?(2)\})'

//Programming: Remove escapes
//Remove backslashes used to escape other characters
preg_replace('\\(.)', '\1', $text);

//Programming: String
//Quotes may appear in the string when escaped with a backslash.
//The string may span multiple lines.
'"[^"\\]*(?:\\.[^"\\]*)*"'

//Programming: String
//Quotes may appear in the string when escaped with a backslash.
//The string cannot span multiple lines.
'"[^"\\\r\n]*(?:\\.[^"\\\r\n]*)*"'

//Programming: String
//Quotes may not appear in the string.  The string cannot span multiple lines.
'"[^"\r\n]*"'

Quotes

//Quotes: Replace smart double quotes with straight double quotes.
//ANSI version for use with 8-bit regex engines and the Windows code page 1252.
preg_replace('[\x84\x93\x94]', '"', $text);

//Quotes: Replace smart double quotes with straight double quotes.
//Unicode version for use with Unicode regex engines.
preg_replace('[\u201C\u201D\u201E\u201F\u2033\u2036]', '"', $text);

//Quotes: Replace smart single quotes and apostrophes with straight single quotes.
//Unicode version for use with Unicode regex engines.
preg_replace("[\u2018\u2019\u201A\u201B\u2032\u2035]", "'", $text);

//Quotes: Replace smart single quotes and apostrophes with straight single quotes.
//ANSI version for use with 8-bit regex engines and the Windows code page 1252.
preg_replace("[\x82\x91\x92]", "'", $text);

//Quotes: Replace straight apostrophes with smart apostrophes
preg_replace("\b'\b", "?", $text);

//Quotes: Replace straight double quotes with smart double quotes.
//ANSI version for use with 8-bit regex engines and the Windows code page 1252.
preg_replace('\B"\b([^"\x84\x93\x94\r\n]+)\b"\B', '?\1?', $text);

//Quotes: Replace straight double quotes with smart double quotes.
//Unicode version for use with Unicode regex engines.
preg_replace('\B"\b([^"\u201C\u201D\u201E\u201F\u2033\u2036\r\n]+)\b"\B', '?\1?', $text);

//Quotes: Replace straight single quotes with smart single quotes.
//Unicode version for use with Unicode regex engines.
preg_replace("\B'\b([^'\u2018\u2019\u201A\u201B\u2032\u2035\r\n]+)\b'\B", "?\1?", $text);

//Quotes: Replace straight single quotes with smart single quotes.
//ANSI version for use with 8-bit regex engines and the Windows code page 1252.
preg_replace("\B'\b([^'\x82\x91\x92\r\n]+)\b'\B", "?\1?", $text);

Escape

//Regex: Escape metacharacters
//Place a backslash in front of the regular expression metacharacters
preg_replace("[][{}()*+?.\\^$|]", "\\$0", $text);

Security

//Security: ASCII code characters excl. tab and CRLF
//Matches any single non-printable code character that may cause trouble in certain situations.
//Excludes tabs and line breaks.
'[\x00\x08\x0B\x0C\x0E-\x1F]'

//Security: ASCII code characters incl. tab and CRLF
//Matches any single non-printable code character that may cause trouble in certain situations.
//Includes tabs and line breaks.
'[\x00-\x1F]'

//Security: Escape quotes and backslashes
//E.g. escape user input before inserting it into a SQL statement
preg_replace("\\$0", "\\$0", $text);

//Security: Unicode code and unassigned characters excl. tab and CRLF
//Matches any single non-printable code character that may cause trouble in certain situations.
//Also matches any Unicode code point that is unused in the current Unicode standard,
//and thus should not occur in text as it cannot be displayed.
//Excludes tabs and line breaks.
'[^\P{C}\t\r\n]'

//Security: Unicode code and unassigned characters incl. tab and CRLF
//Matches any single non-printable code character that may cause trouble in certain situations.
//Also matches any Unicode code point that is unused in the current Unicode standard,
//and thus should not occur in text as it cannot be displayed.
//Includes tabs and line breaks.
'\p{C}'

//Security: Unicode code characters excl. tab and CRLF
//Matches any single non-printable code character that may cause trouble in certain situations.
//Excludes tabs and line breaks.
'[^\P{Cc}\t\r\n]'

//Security: Unicode code characters incl. tab and CRLF
//Matches any single non-printable code character that may cause trouble in certain situations.
//Includes tabs and line breaks.
'\p{Cc}'

SSN (Social security numbers)

//Social security number (US)
'\b[0-9]{3}-[0-9]{2}-[0-9]{4}\b'

Trim

//Trim whitespace (including line breaks) at the end of the string
preg_replace("\s+\z", "", $text);

//Trim whitespace (including line breaks) at the start and the end of the string
preg_replace("\A\s+|\s+\z", "", $text);

//Trim whitespace (including line breaks) at the start of the string
preg_replace("\A\s+", "", $text);

//Trim whitespace at the end of each line
preg_replace("[ \t]+$", "", $text);

//Trim whitespace at the start and the end of each line
preg_replace("^[ \t]+|[ \t]+$", "", $text);

//Trim whitespace at the start of each line
preg_replace("^[ \t]+", "", $text);

URL's

//URL: Different URL parts
//Protocol, domain name, page and CGI parameters are captured into backreferenes 1 through 4
'\b((?#protocol)https?|ftp)://((?#domain)[-A-Z0-9.]+)((?#file)/[-A-Z0-9+&@#/%=~_|!:,.;]*)?((?#parameters)\?[-A-Z0-9+&@#/%=~_|!:,.;]*)?'

//URL: Different URL parts
//Protocol, domain name, page and CGI parameters are captured into named capturing groups.
//Works as it is with .NET, and after conversion by RegexBuddy on the Use page with Python, PHP/preg and PCRE.
'\b(?<protocol>https?|ftp)://(?<domain>[-A-Z0-9.]+)(?<file>/[-A-Z0-9+&@#/%=~_|!:,.;]*)?(?<parameters>\?[-A-Z0-9+&@#/%=~_|!:,.;]*)?'

//URL: Find in full text
//The final character class makes sure that if an URL is part of some text, punctuation such as a
//comma or full stop after the URL is not interpreted as part of the URL.
'\b(https?|ftp|file)://[-A-Z0-9+&@#/%?=~_|!:,.;]*[-A-Z0-9+&@#/%=~_|]'

//URL: Replace URLs with HTML links
preg_replace('\b(https?|ftp|file)://[-A-Z0-9+&@#/%?=~_|!:,.;]*[-A-Z0-9+&@#/%=~_|]', '<a href="\0">\0</a>', $text);

Words

//Words: Any word NOT matching a particular regex
//This regex will match all words that cannot be matched by %REGEX%.
//Explanation: Observe that the negative lookahead and the \w+ are repeated together. 
//This makes sure we test that %REGEX% fails at EVERY position in the word, and not just at any particular position.
'\b(?:(?!%REGEX%)\w)+\b'

//Words: Delete repeated words
//Find any word that occurs twice or more in a row.
//Delete all occurrences except the first.
preg_replace('\b(\w+)(?:\s+\1\b)+', '\1', $text);

//Words: Near, any order
//Matches word1 and word2, or vice versa, separated by at least 1 and at most 3 words
'\b(?:word1(?:\W+\w+){1,3}\W+word2|word2(?:\W+\w+){1,3}\W+word1)\b'

//Words: Near, list
//Matches any pair of words out of the list word1, word2, word3, separated by at least 1 and at most 6 words
'\b(word1|word2|word3)(?:\W+\w+){1,6}\W+(word1|word2|word3)\b'

//Words: Near, ordered
//Matches word1 and word2, in that order, separated by at least 1 and at most 3 words
'\bword1(?:\W+\w+){1,3}\W+word2\b'

//Words: Repeated words
//Find any word that occurs twice or more in a row.
'\b(\w+)\s+\1\b'

//Words: Whole word
'\b%WORD%\b'

//Words: Whole word
//Match one of the words from the list
'\b(?:word1|word2|word3)\b'

//Words: Whole word at the end of a line
//Whitespace permitted after the word
'\b%WORD%\s*$'

//Words: Whole word at the end of a line
'\b%WORD%$'

//Words: Whole word at the start of a line
'^%WORD%\b'

//Words: Whole word at the start of a line
//Whitespace permitted before the word
'^\s*%WORD%\b'