How to Show product options in product list page in wordpress

In this article, we will recommend some effective methods to show options for the configurable and product options in product list. Check them out! Showing options for Configurable products :-

Open content-product.php file you can find this file at this location :-
wp-content\plugins\woocommerce\templates\content-product.php
Copy this code before end of li and after "do_action( 'woocommerce_after_shop_loop_item_title' )"
<?php	
		remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_title', 5 );
		remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_rating', 10 );
		remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_price', 10 );
		remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_excerpt', 20 );
		remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_meta', 40 );
		remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_sharing', 50 );
		do_action( 'woocommerce_single_product_summary' );
	
?>

Odesk PHP Frontend Developer Test v2 answer

In this test there are 4 questions they are following.


Question no 1:- Fantastic three sequence

Solution :-
<?php
function fantastic3($n) {
$series = array(0,1,1,1);
for($i=3 ; $i<=$n ; $i++){
$a = (isset($series[ (int)$i-3 ]))?$series[ (int)$i-3 ]:0;
$b = (isset($series[ (int)$i-2 ]))?$series[ (int)$i-2 ]:0;
$c = (isset($series[ (int)$i-1 ]))?$series[ (int)$i-1 ]:0;
$d = ($a+$b+$c)-1;
if($d<0){
$d = 0;
}
$series[$i] = $d;
}
echo $series[ (int)$n-1 ];
}
// Do NOT call the fantastic3 function in the code
// you write. The system will call it automatically.
?>

how to change shipping method from radio to dropdown in Magento

Today my client want to change shipping method from radio to dropdown on onepage checkout after a lot of googling i not found any proper solution for this.
Then i tried it my self and it's worked for me so i am share my coding here :-
To make shipping method from radio to dropdown copy this file at this location:-

app/design/frontend/your-theme-package/your-theme/template/checkout/onepage/shipping_method/available.phtml

You can download file here.

How to Show product options in product list page in Magento

In this article, we will recommend some effective methods to show options for the configurable and product options in product list. Check them out! Showing options for Configurable products :-

How to Set Up Table Rate Shipping in Magento

In this tutorial, we’re going to look at how to set up table rate shipping in Magento, giving you the ability to charge different shipping rates to individual customers based on their location–from the regional all the way down to the postcode level.

Three ways to price shipping

One thing to note, before we start, is that there are three main ways of setting up table rates–price vs. destination, weight vs. destination and number of items vs. destination.
Essentially what this means is that you can set cheaper shipping to certain destinations if the cost of the item is high, or if the weight and number of items is low.

Configuring table rate shipping

You set table rate shipping inside the System menu accessed via Magento’s backend.
While logged in as admin, navigate to System > Configuration and then, in the left menu under Sales, select Shipping Methods.

Change shipping address dropdown to div in Magento

If you want to change shipping address dropdown to div structure.
After a long research i found that this select box is comming form core php file and it's hard to make any change in core file. So we have to change in shipping.phtml file as following. Step 1 : Open shipping.phtml you can find it :- /app/design/frontend/package/yourtheme/template/checkout/onepage/shipping.phtml Please find this code around line no 30.
  • <?php echo $this->getAddressesHtmlSelect('shipping') ?>
  • Set Payment Method "PayPal" on Particular State Only in Magento

    If you want to disable a specfic payment method for specfic State then follow these steps. 1.Make a new file in app/etc/module/Arunendra_Disablepayment.xml copy and Paste below code in that file
    
    <?xml version="1.0"?>
    
    
         
            true
            local
         
    
    
    
    2.Now make module folder inside app/code/local/Arunendra/Disablepayment 3.Make new folder and file inside app/code/local/Arunendra/Disablepayment/etc/config.xml and copy and paste below code in that file.

    How to disable specfic payment method for specfic products in Magento

    How to disable specfic payment method for specfic products If you want to disable a specfic payment method for specfic products then follow these steps. 1.Make a new file in app/etc/module/Arunendra_Disablepayment.xml copy and Paste below code in that file
    <?xml version="1.0"?>
    
    
    
         
            true
            local
    
        
    
    
    
    2.Now make module folder inside app/code/local/Arunendra/Disablepayment 3.Make new folder and file inside app/code/local/Arunendra/Disablepayment/etc/config.xml and copy and paste below code in that file.

    Add Product Images In Magento Transactional Emails

    In order to add the order Image to the transaction email templates (order), you need to play with the following two files:
    1.) Edit the file: app/design/frontend/base/default/template/email/order/items.phtml Locate this line (Around Line 32) :
    <th align="left" bgcolor="#EAEAEA" style="font-size:13px; padding:3px 9px"> <?php echo $this->__('Sku') &#63></th>
    

    Disable admin notification popup in Magento

    Every time you log in to the Magento Admin Panel, you see an admin notification popop message telling you there's a new Magento version. As a developer, it's best to stay informed about new releases by reading blogs, tweets and lots of other news channels - besides this, upgrades should never be taken lightly. It's possible to remove this notification popup message.


    To remove this notification popup message.
    • Login to your Magento Admin Panel
    • Go to System >> Configuration >> Advanced
    • Disable the Mage_AdminNotification module


    How to create custom page layout in magento

    To create a new custom column layout, you need to place a new file in the Magento theme. With the Magento default theme, you could use the folder app/design/frontend/default/default/template/page, but of course - when building your own site - it is recommended to have your own theme-directory.

    In the tutorial, the file 1column.phtml is copied to the file 1columnfp.phtml (where "fp" stands for the front page). To make this new page reckognizable you wll need to add a new XML-definition. In the tutorial the following code is added to the file app/code/core/Mage/Page/etc/config.xml. copy this module in local exp app/code/local/Mage/Page/etc/config.xml
    
        
        
        page_one_column_fp
    
    
    However, with a Magento upgrade this change could be gone. The same XML could also be added to your app/etc/local.xml file instead:

    Customizing Magento email templates

    Emails (or often referred to as transactional emails) are - just like the entire Magento theme - based on files in the filesystem: If you open up the folder app/locale/en_US/template/email you will numerous files. Don't edit them directly, because any Magento upgrade will override your changes. Instead, the purpose of these files is to override them. You can override these email templates either using the Magento Admin Panel, or by copying them to your Magento theme. The first approach allows for easy editing using the Magento Admin Panel, but this interface lacks nice editing features like syntax highlighting or code completion. Ofcourse, you can copy the textarea contents ofcourse to your local editor modify things there and copy the code back into the textarea once you're done.

    Change order status in WooCommerce for specific payment method

    Copy this code in your theme's function.php file
    <?php
    /* Reset status of new orders from "pending" to "completed" */
    add_action( 'woocommerce_thankyou', 'changeOrderStatus' );
    function changeOrderStatus($order_id) {
        global $woocommerce;
         if (!$order_id )
            return;
     $billing_paymethod = get_post_meta($order_id,'_payment_method',true);
      $order = new WC_Order( $order_id );
      /* put here your specific payment method */
     if($billing_paymethod == 'paypal')
     {
       /* put here your specific  order status */
           $order->update_status( 'completed' );
        }
        else
        {
         /* put here your specfic default order status for all payment method */
      $order->update_status( 'processing' );   
        }
    }
    ?>
    

    Get Upsell products list using Product Id in Magento

    Using Product ID you can get list of Upsell product. Copy following code and place it in you custom file.
    <?php
       // Get product object.
       $object = Mage::getModel('catalog/product');
       
       /* Get product detail using product id   : $_product->getId() */
       $product = $object->load($_product->getId()); 
      
       // Fetch list of upsell product using query.
       $upsell_product = $product->getUpSellProductCollection()->addAttributeToSort('position', Varien_Db_Select::SQL_ASC)->addStoreFilter(); 
    
       //check if record is empty or not
       $count = count($upsell_product); 
       if(empty($count)) : 
           //if empty
           echo "Record not found";
    
       else:
    
         //if result is not empty then get  upsell product detail using foreach loop
          foreach($upsell_product as $_upsell):
             
             //get detail of single upsell prdocut using upsell product id
             $upsp = $object->load($_upsell->getId());
    
             echo "Product Name : ". $upsp->getName();
             echo "Poduct url : ". $upsp->getProductUrl();
             echo "Product regular price : ". $upsp->getPrice();
             
           endforeach;
       
       endif;
    
    ?>
    

    Display all categories and sub categories on left sidebar in Magento

    You can display list of all categories and subcategories in left sidebar including product view page using the following code in Magento. You can display subcategories upto second level using this code. You can create a new file for this code and you can add it in your theme’s catalog XML file like this:

    
    

    How to make accordion tabs in magento For layered navigation

    In this blog I’m going to explain you how to create accordion tabs in magento for layered navigation as displayed below for attributes. Just navigate to your layered navigation file as shown:
    app/design/frontend/default/{your folder}/template/catalog/layer/view.phtml
    


    Then open that that file & paste the following jquery script at the end of the page:
    
    
    #narrow-by-list is the id used in that file(
    )
    . If you used different id’s, replace this with your id and save the file. Refresh the cache and reload the browser to see the results. Use no-conflict method in magento. It is a good practice to avoid javascript conflicts in the page.

    How to create Edit, Delete Cookies in magento

    Understanding Magento Cookies and how to manipulate.
    <?php    
    /**      
    * set cookie      
    * name and value are mandatory; other parameters are optional and can be set as null      
    * $period = cookie expire date in seconds      
    */    
    Mage::getModel('core/cookie')--->set($name, $value, $period, $path, $domain, $secure, $httponly);
    /**
    * get cookie with a specific name
    * $name = name of the cookie
    */
    Mage::getModel('core/cookie')->get($name);
    /**
    * get all cookies as an array
    */
    Mage::getModel('core/cookie')->get();
    /**
    * delete/remove cookie
    * $name is mandatory; other parameters are optional and can be set to null
    */
    Mage::getModel('core/cookie')->delete($name, $path, $domain, $secure, $httponly);
    ?>
    

    How to optimize Magento site

    If you enable Gzip compression by changing .htaccess, you can speed up Magento significantly. Assuming that you have Gzip enabled on your server. Uncomment the part of the code in your htaccess file that matches the code below. You uncomment by removing the #.
    
    
    ############################################
    ## enable apache served files compression
    ## http://developer.yahoo.com/performance/rules.html#gzip
    
         # Insert filter on all content
         SetOutputFilter DEFLATE
         # Insert filter on selected content types only
         AddOutputFilterByType DEFLATE text/html text/plain text/xml
    text/css text/javascript
    
         # Netscape 4.x has some problems...
         BrowserMatch ^Mozilla/4 gzip-only-text/html
    
         # Netscape 4.06-4.08 have some more problems
         BrowserMatch ^Mozilla/4\.0[678] no-gzip
    
         # MSIE masquerades as Netscape, but it is fine
         BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
    
         # Don't compress images
         SetEnvIfNoCase Request_URI \.(?:gif|jpe?g|png)$ no-gzipdont-vary
    
         # Make sure proxies don't deliver the wrong content
         Header append Vary User-Agent env=!dont-vary
    
    
    

    Copy HTTP Request by Expires Headers
    When a customer visits your website for the first time, the site will load lots of HTTP requests. How to minimize these requests? We will use Expires Headers function to save unnecessary HTTP requests for the next visits. Simply add this code to your .htaccess file:
    
    
    ############################################
    ## Add default Expires header
    ##http://developer.yahoo.com/performance/rules.html#expires
    
         ExpiresActive On
         ExpiresDefault "access plus 1 year"
    
    
    
    Reduce the file size of images to be uploaded

    As far as you know, Magento is used for e-commerce website; therefore, all images on the site particular product images are essential. We need eye-catching images, of course, those are sometimes too big to fully load and time-costing. As a result, it is crucial for a store owner to find out a sensible solution to reduce the file size of images to be uploaded but still restrain the quality of the images. It will be critically helpful to reduce site’s capacity when you run it. We suggest a few feasible tips and directions for this issue. Trust us, it is completely simple and all you need is uploading your images to a system and it will return you re sized ones while the quality is kept. Now you can post similar-quality-shrunk images instead of old stone-sized ones. Below are our tips:
    https://tinypng.com/ (PNG images accepted only) http://www.smushit.com/ysmush.it/ (all images accepted)

    Turn off unnecessary modules
    There are thousands of Modules available in Magento to be used or shelved. For the medium-sized e-commerce website, it is not always necessary to use all these extensions and modules. You need to list all Modules that your system won’t use and turn them off. It helps to improve the site loading time when unused extensions are disabled. Simply go to Admin > System >Configuration> Tab Advanced>Advanced>Disable Modules Output, it shows all available Modules and their status. Select unnecessary modules and disable them.

    Utilize Magento Compilation
    Magento compilation will collect all functions in one place, which will decrease steadily site loading time up to 25-50% depending on each system. It is a brilliant feature that helps improve the speed of your site. Go to Admin > System > Tools >Compilation, click Run Compilation Process. When the process is done, you can Disable it.

    Enable Fat Catalog in Admin panel
    This function accelerates products queries and returns time-saving results. Go to Admin >Sytem>Configuration > Catalog: In Frontend section, change 2 values of “Use Flat Catalog Category” and “Use Flat Catalog Product” to Yes:

    And remember to Clear cache before it takes effect.
    Enable Merge CSS and JS
    Magento utilizes a lot of JS and CSS files. Loading each of those files is time-costing, therefore, to minimize the loading time, you can enable Merge function to compress CSS and JS files in one file and it will load at speed of light. Go to Admin >System >Configuration >Developer: Select “JavaScript Settings” and change the value of “Merge JavaScript Files” to Yes. In “CSS Settings”, select Yes for “Merge CSS Files”.

    Clean Database Log
    A Magento website generates a huge amount of logs, so we need to clear these logs regularly to save space of your database and improve the loading time. Go to Admin > System > Configuration >System: In Log cleaning, select Yes for “Enable Log Cleaning” and enter the time frame for logs saving, eg. 14 days.

    When you have applied those above listed solutions, be notified that you need to refresh and enable cache in the Magento back end so that they take effect.
    I hope those methods do help you improve the current site loading time. Besides, you can look for some other utilities to enhance your site optimization, for instance:
    http://www.magentocommerce.com/magento-connect/gtspeed.html http://www.magentocommerce.com/magento-connect/turpentine-varnish-cache.html http://www.magentocommerce.com/magento-connect/full-page-cache-pro.html
    Applying one of these open utilities will partly or mostly accelerate the loading speed of your site, however, be careful as they can conflict with other ready-installed files and make errors in performing your website. Therefore, saving a backup version of your website is always a “lifebuoy” for you before you implement any of those optimizations.

    How to check If is home Page in Magento

    Check If Home Page Magento If you need to determine if the the current page is the homepage in Magento, the below code works.
    <?php
     if(Mage::getSingleton('cms/page')->getIdentifier() == 'home'  && Mage::app()->getFrontController()->getRequest()->getRouteName() == 'cms') {
    echo 'i am home page';
    }
    ?>
    

    How to show product’s rating any where in Magento

    Reviews are another one of numerous excellent features in Magento. Usage of reviews can increase visitors’ trust in your brand, which, in return boosts your sales by a significant amount. Sometimes there is a need for showing star ratings outside the products’ review page. That’s what I’ll be addressing with this article.

    The following code snippet works just about anywhere you have a product loaded (or if you know it’s ID) – cart being one of the examples.

    How to add custom tabs into Magento Product Page

    How to add custom tabs into Magento Product Page The product page is one of the most important parts of your store. That’s why so much attention is paid to make this page look perfect. Tabs is a good way to display a lot of data inside a compact block. It helps to avoid huge scroll bars and also looks much nicer on portable devices. You can find tons of Magento templates with tabs on the product view page and we are going to tell you the easiest way to add them there. All examples are applicable to the default Magento theme, but with practice you can use following methods to customize your own theme. First, go to your store theme folder and find there the following file app/design/frontend/default/yourtheme/layout/catalog.xml. If the file does not exist, you can always copy it from app/design/frontend/base/default/layout/. Note that your own theme can be located within a different path. In the file catalog.xml, find the section:
    
     
    
        
           
                product.tierprices
                
                product.info.addtocart
                product.info.addto
             
    		

    How to add new tab on product view page

    After Magento 1.9 has been released people started asking how to handle the product page tabs since the previous method caused different troubles. The reason is in the modern RWD theme, which goes out of the box with Magento 1.9. It uses slightly different method for adding tabs than in the previous versions. So, let's review how you can easily add own tabs on the product page for RWD-based themes in Magento CE 1.9. First of all, let's make our implementations as clean as possible. To avoid copying of unnecessary pieces of code we will make our changes in the layout file that is being used for custom theme's modifications. You can find this file here: app/design/frontend/[theme_package]/[theme]/layout/local.xml There [theme_package] - it's your package's name and [theme] - it's your theme's name. If there's no such file – just create a clean one. Then, paste the following content in the newly created file:
    <?xml version="1.0"?> version="1.0"?>
    
        
            
                
                    detailed_info
                    The New Tab
                
            
        
    
    
    In case if this file already exists – just add the content between (including them) inside of node. As you can see, we have added a block with the class 'core/template' (Mage_Core_Block_Template) inside of the group called 'detailed_info'. That group is a built-in templates group for the product page tabs. You can use any name for your tab, just ensure that it's unique ('the_new_tab' in our example). Then, we have assigned the template file for our tab where the tab's content is placed – 'atwix/newtab.phtml'. Finally, we have set the name for our tab using the standard method 'setTitle()', so the name is 'The New Tab'. On the last step, we need to check if our product view template contains the tabs output logic. Open the following file: app/design/frontend/[theme_package]/[theme]/template/catalog/product/view.phtml

    Login as a customer from Magento admin

    Often there are situations where customer has some issues while placing orders or making operations from the “My Account” section. At that point, an ability for admin to login as a customer and see what is wrong becomes very useful. Sure, you can make a universal password logic, but that method has heavy security risks. Not so long ago, we’ve noticed that Magento has ability to load and use customer’s sessions different way. We will tell you how to create a simple extension for logging in as a customer from Magento admin. Step 1 For example, let’s call our module Arun_Ulogin. As always we must start by creating a module descriptor in app/etc/modules folder. So put the Arun_Ulogin.xml file into this directory. The file will be with the following content:
    <&#63xml version="1.0"?>
    
        
             
                true
                community
              
        
    
    

    Overriding Magento observers

    As you may know, we need to override the Magento observers when we deal with the extension’s conflicts or want to disable (or modify) a part of some extension’s functionality. Usually, there is no difference between the observer’s overriding and overriding of any other regular model. But sometimes we can face with the issues working with the simple override. How should we act then to keep it conventionally? Let’s check the following step by step instruction for Magento observers overriding. First of all, we should pay attention to the naming. Let’s assume that we have some 3rd party extension. It is named Some_Extension, and this extension has the following observer:
    <&#63php
    /**
     * file path:
     * magento_root/app/code/local/Some/Extension/Model/Observer.php
     */
     
    class Some_Extension_Model_Observer
    {
       public function someMethod( $observer )
       {
          /** 
           *Do some stuff here 
           */
             
          return $observer;
       }
    }
    &#63>
    

    How to rewrite url in Magento

    Follow these instruction to rewrite url. Step 1:- Make a new category named with "laptop" and save it. Step 2:- Go to Catalog->Url rewrite management.And find your newly created category and click on it. more instruction see in below pic.


    Some useful and important code in magento

    Some useful and important code in magento :-
    <&#63php  
    Magento Home URL 
    - Mage::getBaseUrl();
     
    Magento Home Directory 
    - Mage::getBaseDir();
     
    URL of a file in the skin directory
    - $this->getSkinUrl('images/myfile.png'); // in a template or Block
    - Mage::getDesign()->getSkinUrl('images/myfile.png'); // from anywhere
     
    Format a price value
    - Mage::helper('core')->formatPrice($amount);
     

    How to insert,update,delete and show data in Magento

    Suppose, I have a module named mynews. Here follows the code to select, insert, update, and delete data from the news table
    1. INSERT DATA
    $data contains array of data to be inserted. The key of the array should be the database table’s field name and the value should be the value to be inserted.
    <&#63php
    $data = array('title'=>'hello there','content'=>'how are you? i am fine over here.','status'=>1);
    $model = Mage::getModel('mynews/mynews')->setData($data);
    try {
        $insertId = $model->save()->getId();
        echo "Data successfully inserted. Insert ID: ".$insertId;
    } catch (Exception $e){
     echo $e->getMessage();   
    }
    &#63>
    

    How to insert your block into any place in Magento

    Hello guys, it’s time to tell you how to insert block into any place you want in Magento. As you know, very often we need to set some block into selected weird place without editing template, so we’ll try to describe the way how to do this using layouts and observers.In our case, for such experiments will be used category page. Let’s say, you need to place your block inside the other one and this block is instance of the Mage_Core_Block_Text_List class. That means, the block renders his children automatically, what’s easy. Then, you just need to follow the steps which are below:
    
        
    
    
    This block will be displayed after all content of the “left“ block. But, what if we need it to be displayed before all content – just add the “before” directive. See below such example:

    Important operatinol functions of Magento

    1.How to get the category url in magento
    <?php echo Mage::getModel('catalog/category')->load($catId)->getUrl() ?>
    
    2.How to remove .html at the end of the url in magento
    System => Configuration => Catalog => Search Engine Optimization and empty the fields "Product URL Suffix" and "Category URL Suffix"
    3.How to get category’s Thumbnail image in magento
    <?php $thumbnail=Mage::getModel('catalog/category')->load($categoryId)->getThumbnail();  //$category_Id -category id ,$thumbnail – image name
    if($thumbnail !=''){
    $imgPath = Mage::getBaseUrl('media').'catalog/category/'  // Get category image path
    echo '';
    ?>
    
    4.How to get Customer Details By Session
    <?php  $customer = Mage::getSingleton('customer/session')->getCustomer();
        print_r($customer);?>
    
    4.1How to get Customer Details By E-Mail
    <?php   $customer = Mage::getModel('customer/customer')->loadByEmail(example@mail.com);
        print_r($customer); ?>
    
    5.How to delete product by sku :-
    <?php  $product = Mage::getModel('catalog/product');
       $productId = intval($product2->getIdBySku('putSkuHere');
       $product->load($productId)->delete(); ?>
    
    6.How to get module table :-
    <?php  
    $resource = Mage::getSingleton('core/resource');
    $tableName = $resource->getTableName('mymodule/mymodel') 
    ?>
    

    how to upload any file in magento

    Step 1 :- cretae html form for upload file
    Step 2 :- Write Script for upload file
    <?php
    
    if(isset($_FILES['myfilename']['name']) && $_FILES['myfilename']['name'] != '')
    {  
    try
        {      
            $path = Mage::getBaseDir('media') . DS . 'csvfile' . DS;  //desitnation directory    
            $fname = $_FILES['myfilename']['name']; //file name
      $filpath = $path.$fname;
            $uploader = new Varien_File_Uploader('myfilename'); //load class
            $uploader->setAllowedExtensions(array('xls','xlsx','csv')); //Allowed extension for file
            $uploader->setAllowCreateFolders(true); //for creating the directory if not exists
            $uploader->setAllowRenameFiles(false); //if true, uploaded file's name will be changed, if file with the same name already exists directory.
            $uploader->setFilesDispersion(false);
            $uploader->save($path,$fname); //save the file on the specified path
        }
        catch (Exception $e)
        {
            echo 'Error Message: '.$e->getMessage();
        }
    }
    ?>
    

    How to create category from csv file

    How to create bulk parent and sub category from csv file
    Instruction:- Copy and save this code file in root folder of Magento and run it. exp :- http://yoursite/cat.php
    <?php
    error_reporting(E_ALL | E_STRICT);
    $mageFilename = 'app/Mage.php';
    require_once $mageFilename;
    $app = Mage::app('admin'); 
    Mage::setIsDeveloperMode(true);
    ini_set('display_errors', 1);
    ini_set('max_execution_time', 1800);
    umask(0);
    /************ Get CSV file **************/
      $path = Mage::getBaseDir('media') . DS . 'catcsvfile'; //file path of csv
      $files = glob($path.'/*'); // get all file names
      if($files){
       foreach($files as $file){ // iterate files   
         $csv  =  new Varien_File_Csv();
         $data =  $csv->getData($file); //path to csv
            }  
     array_shift($data);
     foreach($data as $_data){
    /*****************  Prent category creation *****************/
       /*****************  Prent category creation *****************/
       $Pcat =  utf8_encode($_data[0]); // column to create parent category
       $getcategory = Mage::getResourceModel('catalog/category_collection')->addFieldToFilter('name',$Pcat);
       $catData = $getcategory->getData();
       $catcount  = count($catData);
        if($catcount==0 && !empty($Pcat))
       {  $category = Mage::getModel('catalog/category');
         $category->setName($Pcat);
         $category->setUrlKey($Pcat);
         $category->setMetaTitle($Pcat);
         $category->setIsActive(1);
         $category->setDisplayMode('PRODUCTS');
         $category->setIsAnchor(1); //for active achor
         $category->setStoreId(Mage::app()->getStore()->getId());
         $parentCategory = Mage::getModel('catalog/category')->load(2);
         $category->setPath($parentCategory->getPath());
         $category->save();
      }
    /*    Child category creation             **********************/
       global $childcat;
        $childcat = utf8_encode($_data[1]); // column to create sub category
       $pgetcategory = Mage::getResourceModel('catalog/category_collection')->addFieldToFilter('name',$childcat);
       $pcatData = $pgetcategory->getData();
       if(!$pcatData) {
        $getcategory2 = Mage::getResourceModel('catalog/category_collection')->addFieldToFilter('name',$Pcat);
        $catData2 = array();
       $catData2 = $getcategory2->getData();
       if(!empty($catData2)){
       $ParentCategoryId2 = $catData2[0]['entity_id'];   
         $category = Mage::getModel('catalog/category');
         $category->setName($childcat);
         $category->setUrlKey($childcat);
         $category->setMetaTitle($childcat);
         $category->setIsActive(1);
         $category->setDisplayMode('PRODUCTS');
         $category->setIsAnchor(1); //for active achor
         $category->setStoreId(Mage::app()->getStore()->getId());
         $parentCategory = Mage::getModel('catalog/category')->load($ParentCategoryId2);
         $category->setPath($parentCategory->getPath());
         $category->save();
       }  
       }
     }
    }
    else
    {
    echo 'file not found';
    }
    ?>
    

    How to get category id by category name in magento

    <?php
    $category = Mage::getResourceModel('catalog/category_collection')->addFieldToFilter('name','cateNameHere'));
        $catData = $category->getData();      
     $categoryId = $catData[0][entity_id];
     echo $categoryId;
     ?>
    

    How to delete all category in magento

    Instruction :- Copy and save this code file in root folder of Magento and run it; exp :- http://yoursite/deletecat.php
    <?php 
    error_reporting(E_ALL | E_STRICT);
    $mageFilename = 'app/Mage.php';
    require_once $mageFilename;
    Mage::setIsDeveloperMode(true);
    ini_set('display_errors', 1);
    ini_set('max_execution_time', 1800);
    umask(0);
    Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
    foreach(Mage::getModel('catalog/category')
    ->getCollection()
    ->addFieldToFilter('entity_id', array('gt' => 2)) as $cat) {
    $cat->delete();
    }
    ?>
    

    How to write secure code in Php -1

    PHP is a very easy language to learn, and many people without any sort of background in programming learn it as a way to add interactivity to their web sites. Unfortunately, that often means PHP programmers, especially those newer to web development, are unaware of the potential security risks their web applications can contain. Here are a few of the more common security problems and how to avoid them.

    Rule Number One: Never, Ever, Trust Your Users
    It can never be said enough times, you should never, ever, ever trust your users to send you the data you expect. I have heard many people respond to that with something like "Oh, nobody malicious would be interested in my site". Leaving aside that that could not be more wrong, it is not always a malicious user who can exploit a security hole - problems can just as easily arise because of a user unintentionally doing something wrong.

    How to write secure code in Php -2

    Learn how to improve your security a little further with the second part of this PHP tutorial.
    In Writing Secure PHP, I covered a few of the most common security holes in websites. It's time to move on, though, to a few more advanced techniques for securing a website. As techniques for 'breaking into' a site or crashing a site become more advanced, so must the methods used to stop those attacks.


    File Systems
    Most hosting environments are very similar, and rather predictable. Many web developers are also very predictable. It doesn't take a genius to guess that a site's includes (and most dynamic sites use an includes directory for common files) is an www.website.com/includes/. If the site owner has allowed directory listing on the server, anyone can navigate to that folder and browse files.

    How to write secure code in Php -3

    The third part of the Writing Secure PHP series, covering weak passwords, clients and more advanced topics.
    In How to write secure code in Php-1, 2  and 3 I covered many of the basic mistakes PHP developers make, and how to avoid common security problems. It is time to get a little deeper into security though, and begin to tackle some more advanced issues.
    Context
    Before I start, it is worth mentioning at this point in this series that much of what is to come is highly dependant on context. If you are running a small personal site and are regularly backing it up, the chances are that there is no real benefit to you spending weeks on advanced security issues. If an attacker can gain nothing (and cause no harm) by compromising your site, and it would only take you ten minutes to restore it, should something go wrong, then it would be a waste to spend too long on security concerns. At the other end of the scale, if you are managing an ecommerce site that processes thousands of credit cards a day, then it is negligent not to spend a lot of time researching and improving your site's security.

    How to wright secure code in Php-4


    Cross-Site Scripting (XSS)
    Cross-site scripting (often abbreviated to XSS) is a form of injection, where an attacker finds a way to have the target site display code they control. In its most basic form, this can be as simple as a site that allows HTML characters in usernames, where someone can specify a username like:
    DaveChild<script type="text/javascript" src="http://www.example.com/my_script.js"></script>
    Now, whenever someone sees my username on the target site, the script I've added to my username will run. I could potentially use this to grab the person's login information, log their keystrokes - any number of nefarious activities.

    How to make a xml file in php

    Here is the PHP code you can customize it according to your requirements.

    <&#63php
    $xml = new SimpleXMLElement('<root/>');
    
    $track = $xml->addChild('track');
    
    $track->addChild('fieldName1','fieldValue');
    
    $track->addChild('fieldName2','fieldValue');
    
    $track->addChild('fieldName3','fieldValue');
    
    $track->addChild('fieldName4','fieldValue');
    
    Header('Content-type: text/xml');
    
    print($xml->asXML());
    
    &#63>
    
    Enjoy Coding ..!!

    Form validation in Magento

    As we know that Magento use Prototype.js as javascript library. It provides a simple way to validate html form values. Below is an example:


    How to Override/Overwrite Core Class In Magento ?


    There are many reasons and it’s a bad habit and bad programming if core files are modified and it’s not recommended at all. Therefore Magento brought in an excellent way how to override/overwrite those files.In  this post we learn how to override product Model class.This module we will change   first character of product name in uppercase.

     Override/Overwrite Magento Model Class.

    How to make an Observer in Magento ?


     Today i am going to show how to make an observers in Magento. 

    In this module we are going to make _load_after event to suffix something with product name in front-end area.In same way you can make any observer.

    How to make Paypal Recurring system for any site.


    Hello every one today i am going to tell you how to make paypal recurring method for any site you can easily iterated this method to any website.

    How to run direct MySQL Queries in Magento




    While developing custom solutions for Magento, developers should always think about performance. There are many areas that we can focus on: block caching and removing unnecessary blocks from layout, disabling unused modules, database-related optimisation. Let's talk about the database-related optimisation, about direct SQL queries in particular.

    How to create an attribute field for customer account in Magento


    Follow these steps to create attribute :
    Step 1: Create this file and save on this location app\etc\modules\Excellence_Profile.xml


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

    How to Make Custom admin theme in Magento


    Follow these steps :-
     
    Step 1:- Save this file in app/etc/modules/Smart_Admintheme.xml

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


    How to enable tempalte and block path hints in Magento

    Run this query in your database.

    INSERT INTO core_config_data (scope, scope_id, path,value)

    VALUES ('default', 0, 'dev/debug/template_hints', 1),
    ('default', 0, 'dev/debug/template_hints_blocks', 1);

    To disable them again, run this query:
    UPDATE core_config_data set value = 0 where scope = 'default' and scope_id = 0 and path ='dev/debug/template_hints'

    To enable again run this query:
    UPDATE core_config_data set value = 1 where scope = 'default' and scope_id = 0 and path ='dev/debug/template_hints'

    How to update inventory, Price using custome attribute in magento


    Step 1: Create a test.csv file as you  see in above  picture in magento root directory.
    Step 1: Create a test.php  file  in magento root directory.

    How to get Controller, Module, Action & Router Name in Magento

    In most of the case you need to know the name of controller or module in order to debug. Simple one line code to get these.
    1. Get Controller Name In Template Files:
    $this->getRequest()->getControllerName();

    2. Get Action Name In Template Files:
    $this->getRequest()->getActionName(); //the function inside the controller

    3. Get Router Name In Template Files:
    $this->getRequest()->getRouteName();

    Adding links to the Top menu in Magento


    One of the things that may sound easy to set are the top menu items, or the main menu items if you prefer.

    Custom category menu navigation in Magento


    Magento has its top menu reserved for category navigation. It’s pretty solid for displaying categories, even when there is a large number of them.

    Change Base url in magento using database.

    How to change Unsecure  “base url” and Secure “Base url” In magento using databse.
    1.       Open Database and find “core_config_data” table. In this table find “web/unsecure/base_url” and “web/secure/base_url” under “Path” column.
    2.       Under value column change your desire url.
    3.       Save data

    Finsish 

    Newsletter auto-subscribe on create account and place order in Magento


    By default Magento provides a Newsletter feature, which enables store administrators to send newsletters to customers who have registered to receive them. Since most customers tend not to opt-in to any email subscription related services, you might need to automatically subscribe customers when they register or place an order. In this article I’ll present code and simple Magento extension to make it easier for you to accomplish this task.

    How to Add a ‘New Product’ Icon in Magento for New Products

    1. Manage attributes

    Go to Catalogue -> Attributes -> Manage Attributes. Set up a new attribute at this page and call it ‘Boolean’. Set its ID as new_product. Under your advanced options, you will have the option to select it as a front end product. Do this. Now you simply have to add the new attribute to your custom attribute if you are using one. If not, set it to default. Save the new product.
    You will now have a new product in your catalogue which has a Boolean flag set to yes. The next stage involves taking this new product icon and putting it in your front end.
    2. Make it show
    Now that you have a product icon with a Boolean flag, it’s time to make this show on your front end. This is achieved by accessing template files: templates/catalog/product/list.phtml and templates/catalog/product/view/media.phtml.
    <div class="product-image">

    <?php if($_product->getNewProduct()) { ?>

    <div class="new-product"></div>

    <?php } ?>

    <?php

    $_img = '<img id="image" src="'.$this->helper('catalog/image')
    ->init($_product, 'image').'"
    alt="'.$this->htmlEscape($this->getImageLabel()).'"
    title="'.$this->htmlEscape($this->getImageLabel()).'" />';

    echo $_helper->productAttribute($_product, $_img, 'image');

    ?>

    </div>
    As you can see, above, your new product is shows in ‘$_product->getNewProduct’. The next step is to ensure that your CSS is set up to show your product with Boolean flag. You need to make the product_class relative to the position of the icon. So:

    .products-grid .product-image { position: relative; display:block; width:244px; height:156px; margin:0 0 10px; }

    .new-product {

    position: absolute;

    right: 0;

    top: 0;

    width: 65px;

    height: 66px;

    display: block;

    z-index: 2;

    background: url(../images/new-product.png) no-repeat;
    3. Save
    Save your changes and ensure that your code is correct before doing so. Now, every time you add a new product and it goes on sale through your front end, it’ll have an icon and Boolean flag.


    Magento - Can't login to admin in localhost

    I am currently working on magento version 1.3.2.4. When i login to admin, it looks like i have entered proper username and password because it doesn't show any error like "Invalid username or password". When i try with fake login I do get error. Even i am not getting any error it stays on the login page.
    So, I had to go through code and comment out few lines after which I was able to login and access admin again.
    app\code\core\Mage\Core\Model\Session\Abstract\Varien.php line 77: original:
    // set session cookie params
    session_set_cookie_params(
        $this->getCookie()->getLifetime(),
        $this->getCookie()->getPath(),
        $this->getCookie()->getDomain(),
        $this->getCookie()->isSecure(),
        $this->getCookie()->getHttponly()
    );

    Commented out three lines:
    // set session cookie params
    session_set_cookie_params(
        $this->getCookie()->getLifetime(),
        $this->getCookie()->getPath() /*,
        $this->getCookie()->getDomain(),
        $this->getCookie()->isSecure(),
        $this->getCookie()->getHttponly()*/
    );

    Hide "Showing posts with label" message in blogger

    • First go to Template > Edit HTML
    • In Blogger default templates, search for <body> and in custom templates, search for <body>
    • Add the below code just after above code.
    <b:if cond='data:blog.pageType == &quot;index&quot;'>
    <b:if cond='data:blog.searchLabel'>
    <style>
    .status-msg-wrap{display:none;}
    </style>
    </b:if>
    </b:if>
    Now Save the template and check the result by clicking any of your labels 

    How to call an attributes on product page in Magento

    Create a new attribute or find a existing attribute to call on product page.

    Step 1:- First of all go to catalog->attributes->manage attributes on this page you will see a list of attributes under attribute code you will see all the attribute code copy any code. For example “cost” to display it on front end on product view page.

    Step 2:- Open \template\catalog\product\view.phtml now find this code line.

    “<?php $_product = $this->getProduct(); ?>”

    After this code we call our attribute by this code.

    <?php
    If($_product->getCost ()):
    echo $_product->getCost ()
    endif;
    ?>


    That’s it.

    How to make a module in Magento Part 1

    So here is our file and folder structure for module.


    A)     app\etc\modules\Summer_Spring.xml (Create a file for Module Configuration file).
    B)     \app\code\local\Summer (Create a namespace folder).C)     \app\code\local\Summer\Spring (Create a module folder).D)     \app\code\local\Summer\Spring\controllers (Create a controller folder).E)      \app\code\local\Summer\Spring\etc (Create a Configuration folder).F)      \app\code\local\Summer\Spring\etc\config.xml (Create a Configuration file).G)    \app\code\local\Summer\Spring\controllers\IndexController.php (Create a Controller file).

    How to install Magento On wamp Server.

    Please follow these instruction to install Magento on local Server,  

    Step 1:- For Download magento go To             http://www.magentocommerce.com/download and download latest version.

    Step 2:- Extract Magento folder and copy in your localhost folder.
    Step 3:- Create database in phpnyadmin database name should be in lower case.
    Before go further we have to make some changes So let’s do it now.

    How to Setup multiple Store in Magento

    Please Follow these steps to create  multiple Store  in Magento.
    Step 1:- Login in admin panel Go to Catalog and click on manage categories.
      
    Step 2:- Now click on Add Root Category button.
    Step 3:- On general information page fill name for category For example:-
    Name = arunstore,
    Is Active = Yes
    Page Title = Arun store
    Include in Navigation Menu = Yes

    Remove sidebar content block In Magento.

    If you want to remove any Block from you home page, cart page or Product view page  it’s so simple just go to your layout folder find your xml file and add remove following method for exp see below.We are going to remove Pool Block from “Product view page” and home page. I am currently using “2-columns-right” template for my home page so follow these steps :-

    Step 1 :- Go to your \app\design\frontend\<your theme package>\<your theme>\layout\poll.xml and now open “poll.xml” add following code between </layout> code….</layout>.
    <!-- Remove poll block from product view page -->                 <catalog_product_view> <!--- You can find this in catlog.xml  ->                  <reference name="right">                 <action method="unsetChild"><name>right.poll</name></action>                </reference>                </catalog_product_view><!--remove poll block from page two columns right page-->                 <page_two_columns_right> <!--- You can find this in page.xml  ->                   <reference name="right">                 <action method="unsetChild"><name>right.poll</name></action>                </reference>                 </page_two_columns_right>

    By using same method you can remove your block another method to disable your module block follow these steps .

    Step 1 :- Go to Your admin  and then Go System and click on drop down menu Configuration  and find Advance from left side bottom click on it.
    Step 2 :- Click on Disable Module Output find your module for example I am disabling poll module “Mage_Poll” uncheck the box now select disable from drop down and now click on save config button.
    Now go to your website and refresh it you will see the change.