Magento 1.9- How to allow orders for out-of-stock products?

Magento has in-built setting for turning on "Backordering".

By changing the settings in System > Config > Inventory will only affect the defaults when you create new products, you still need to enable each product to allow backorders.

Easiest way to do this is select all products you want to allow to be backordered, then select Update attributes from the actions drop down and click submit.

Once the screen has loaded select the Inventory tab from the top left. Then select the change box for 'Backorders' and then click save.

Magento 1.9- If product $0 instead of showing price show 'Contact Us For Price'

If product $0 instead of showing price show 'Contact Us For Price'.

Not sure but it might be due to ===. In this case == should be more than enough.

Instead of comparing a string try and use the finalPrice value which is numeric. It would also prevent any issues if the format of your price HTML ever changes.

if ($_product->getFinalPrice() == 0) { 
    echo '

Contact Us For Price

'; }else{ echo $this->getPriceHtml($_product); }

Magento 1.9 : Remove index.php from url

If you want to access your magento URL without index.php

for example:

http://domain.com/index.php/category

to

http://domain.com/category

then use the following steps

1) Login to admin section by using the URL

http://domain.com/index.php/admin

2) then go to “System >> Configuration >>Web >> Search Engines Optimization”

Use Web Server Rewrites : YES

3) Go to “System >> Configuration >>Web >>Secure”

Use secure URL Frontend: YES

4)Then create the .htaccess file under your the magento installed folder. If the magento installed under document root ( /home/username/public_html) then add follogig rules into .htaccess file


<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

and If the magento installed under /shop or directory then add the following rules into ” /home/username/public_html/shop/.htaccess ” file.


<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /shop/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /shop/index.php [L]
</IfModule>

Compare data in Excel in two columns to find duplicates

To use a formula to compare the data in two columns:

1)In a new worksheet, enter the following data (leave column B empty):

X1: 1   Y1:     Z1: 3
X2: 2   Y2:     Z2: 5
X3: 3   Y3:     Z3: 8
X4: 4   Y4:     Z4: 2
X5: 5   Y5:     Z5: 0

2)Type the following formula in cell B1:

=IF(ISERROR(MATCH(X1,$Z$1:$Z$5,0)),"",X1)

3)Select cells

Y1:Y5.

4)The duplicate numbers are displayed in column B, as in the following example:

 
X1: 1   Y1:      Z1: 3
X2: 2   Y2:2     Z2: 5
X3: 3   Y3:3     Z3: 8
X4: 4   Y4:      Z4: 2
X5: 5   Y5:5     Z5: 0 

Excel extract words before and after a specific word

For example, we have the following text in a cell “A1″ and you’d like to extract the text before the comma (the last name):
Husain, Aftab
To extract the last name before the comma “Husain” from A1, use one of the following formula:
 =LEFT(A1,(FIND(",",A1,1)-1)) 
The result: Husain
To extract the first name after the comma from A1, use one of the following formula:
=MID(A1,FIND(",",A1)+2,256) 
The result: Aftab

Redirect non www to www url

It is very important from SEO point of view for a site to open from single URL. If we want that uor site should only open with www preceding the url we should just copy and paste the code below in our .htaccess file and you are done.For example if a site opens with 'abc.com' and also with 'www.abc.com' and you want that it should always open with 'www.abc.com' and if one tries to open with 'abc.com' it should redirect it to 'www.abc.com'.

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} !^www\.(.*)$ [NC]
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

RewriteCond %{HTTPS} on
RewriteCond %{HTTP_HOST} !^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]

Do not mesh previous session magento 1.9 with current cart

If you want that the current cart items not to mesh up with previous session when you log on , replace your

 app/code/core/Mage/Checkout/Model/observer.php 

file code with this one and you are done.

What we wanted was to prevent the cart from the old session from merging into the cart of the current session at the point when thecustomer login

/**
 * Magento
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Open Software License (OSL 3.0)
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/osl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@magentocommerce.com so we can send you a copy immediately.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade Magento to newer
 * versions in the future. If you wish to customize Magento for your
 * needs please refer to http://www.magentocommerce.com for more information.
 *
 * @category   Mage
 * @package    Mage_Checkout
 * @copyright  Copyright (c) 2008 Irubin Consulting Inc. DBA Varien (http://www.varien.com)
 * @license    http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
 */

/**
 * Checkout observer model
 *
 * @category   Mage
 * @package    Mage_Checkout
 * @author      Magento Core Team 
 */
class Mage_Checkout_Model_Observer
{
    public function unsetAll()
    {
        Mage::getSingleton('checkout/session')->unsetAll();
    }

    public function loadCustomerQuote()
    {
        $lastQid = Mage::getSingleton('checkout/session')->getQuoteId(); //quote id during session before login;
        if ($lastQid) { //before login session exists means cart has items                            
            $customerQuote = Mage::getModel('sales/quote')
                ->loadByCustomer(Mage::getSingleton('customer/session')->getCustomerId()); //the cart from last login         
            //set it to the session before login and remove its items if any
            $customerQuote->setQuoteId($lastQid);
            $this->_removeAllItems($customerQuote);
            
        } else { //no session before login, so empty the cart (current cart is the old cart)
            $quote = Mage::getModel('checkout/session')->getQuote();                                
            $this->_removeAllItems($quote);
        } 
    }

    protected function _removeAllItems($quote){
        //reset all custom attributes in the quote object here, eg:     
       // $quote->setDestinationCity('');
        
        foreach ($quote->getAllItems() as $item) {
            $item->isDeleted(true);
            if ($item->getHasChildren()) foreach ($item->getChildren() as $child) $child->isDeleted(true);
        }
        $quote->collectTotals()->save();        
    } //_removeAllItems
    
    
    public function salesQuoteSaveAfter($observer)
    {
        $quote = $observer->getEvent()->getQuote();
        /* @var $quote Mage_Sales_Model_Quote */
        if ($quote->getIsCheckoutCart()) {
            Mage::getSingleton('checkout/session')->getQuoteId($quote->getId());
        }
    }
}

Magento Import Tier Price

Below is the code to Magento Import Tier Price from csv

//Magento Import Tier Price from csv
require_once 'app/Mage.php';
umask(0);
Mage::app('default');

if(isset($_FILES["file"]) && !empty($_FILES["file"]))
{ 
 if ($_FILES["file"]["error"] > 0)
  {
  echo "Return Code: " . $_FILES["file"]["error"] . "
"; } else { echo "Upload: " . $_FILES["file"]["name"] . "
"; echo "Type: " . $_FILES["file"]["type"] . "
"; echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb
"; echo "Temp file: " . $_FILES["file"]["tmp_name"] . "
"; if (file_exists("var/export/" . $_FILES["file"]["name"])) { echo $_FILES["file"]["name"] . " already exists. "; } else { move_uploaded_file($_FILES["file"]["tmp_name"], "var/export/" . $_FILES["file"]["name"]); echo "Stored in: " . "var/export/" . $_FILES["file"]["name"]; } } $tableName = Mage::getSingleton('core/resource') ->getTableName('catalog_product_entity_tier_price'); function CSVImport($table, $fields, $csv_fieldname='csv') { $handle = fopen("var/export/".$_FILES["file"]["name"],'r'); if(!$handle) die('Cannot open uploaded file.'); $row_count = 0; $rows = array(); while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { $row_count++; $records[] = $data; foreach($data as $key=>$value) { $data[$key] = "'" . addslashes($value) . "'"; } $rows[] = implode(",",$data); } fclose($handle); if(count($records)) { foreach($records as $key=>$value) { $tierprice[$value[4]][]=array( 'website_id' => 0, 'price_qty' => $value[8], 'price' => $value[9] ); } foreach($tierprice as $key=>$value) { $productid = Mage::getModel('catalog/product') ->getIdBySku($key); if($key=='sku') { continue; } foreach($value as $key1=>$val1) { $query = "insert into $table set entity_id='".$productid."', all_groups=1, qty=$val1[price_qty], value=$val1[price]"; $write = Mage::getSingleton('core/resource')->getConnection('core_write'); $write->query($query); } } print 'Successfully imported '.(int)($row_count-1).' record(s)'; } else { print 'Cannot import data - no records found.'; } } CSVImport($tableName, array('entity_id','all_groups','customer_group_id','qty', 'tier_type', 'value' ,'website_id'), "csv_file"); }
Tier Price Import

Magento export tier price

Below is the code to Magento export tier price of all product to csv

//Magento export tier price of all product to csv
require_once 'app/Mage.php';
umask(0);
Mage::app('default');

header("Content-type:text/octect-stream");
header("Content-Disposition:attachment;filename=data.csv");

$tableName = Mage::getSingleton('core/resource')
         ->getTableName('catalog_product_entity_tier_price');
 $storeId    = Mage::app()->getStore()->getId();
 $product    = Mage::getModel('catalog/product');
 $products   = $product->getCollection()->addStoreFilter($storeId)->getAllIds();
 
 $fieldname = array("store","websites","attribute_set","type","sku","name","tier_price_website","tier_price_customer_group","tier_price_qty","tier_price_price");
 print stripslashes(implode(',',$fieldname)) . "\n";
 foreach($products as $productid)
 {  
  $existingTierPrice = $product ->load($productid)->tier_price;
  $sku = $product->getSku();
  $name = $product->getName();
  foreach($existingTierPrice as $key=>$value)
   {   
   $tierarray = array("admin","base","Default","simple",$sku,$name,"all","all",$value['price_qty'],$value['price']);
   print stripslashes(implode(',',$tierarray)) . "\n";
   }  
 }

PHP Code - Generate XML from database

Below is PHP code to generate XML from database.

header("Content-type: text/xml");

mysql_connect('hostname','user','password');
mysql_select_db('database_name');
$query = mysql_query("select * from table_name");

   

  $domtree = new DOMDocument('1.0', 'UTF-8');
  $xmlRoot = $domtree->createElement("xml");
  $xmlRoot = $domtree->appendChild($xmlRoot);
  $currentTrack = $domtree->createElement("itemset");
  $currentTrack = $xmlRoot->appendChild($currentTrack);  

 while($row = mysql_fetch_assoc($query))
    {
        $currentTrack1 = $currentTrack->appendChild($domtree->createElement("item")); 
        foreach($row as $index=>$val)
            {
                $currentTrack1->appendChild($domtree->createElement($index,$val));

            }
    }  

 echo $domtree->saveXML();

Magento #1146 - Table doesn't exist

I faced a very irritating issue. When I logged in phpmyadmin and looked at a table in left column the table shows. But when I try to open that table by clicking on it , it throws error "#1146 - Table `DB NAME.tag_summary` doesn't exist "

I tried to drop the table and create the table again but it throws same error "#1146 - Table `DB NAME.tag_summary` doesn't exist".

Below is the solution:

You would need to access the server via SSH and after that navigate to /var/lib/mysql and go to the database folder.

For eg: cd /var/lib/mysql/DATABASE Folder and then delete the table using

rm -rf DB NAME.tag_summary

rm -rf DB NAME.tag_summary.ibd

rm -rf DB NAME.tag_summary.frm

Then connect to mysql by using the command mysql and follow the below steps:

use DB NAME;

DROP TABLE DB NAME.tag_summary;

Magento 1.9 : 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/CustomerGroupsPrice/Model/Observer.php

Refresh Cache and the sorting is perfect.

Magento Installation Linux/Ubuntu : Enable curl

If we get the error "curl cannot be loaded" just run the below command in your linux terminal and the error will disappear.

I run the below query and the issue resolved.

sudo apt-get install curl libcurl3 libcurl3-dev php5-curl

Magento 1.9 : 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;

php function to find Relative time in year, month, week, day etc

function to find time passed or time left between two time.from & to are two arguments.

to is optional and defaults to current time stamp if not given

 echo time_relative("May 3, 1985 4:20 PM");

convert time to maonth days weeks

 function time_relative($from, $to = null)
 {
  $to = (($to === null) ? (time()) : ($to));
  $to = ((is_int($to)) ? ($to) : (strtotime($to)));
  $from = ((is_int($from)) ? ($from) : (strtotime($from)));
  $output = '';

  $units = array
  (
   "year"   => 29030400, // seconds in a year   (12 months)
   "month"  => 2419200,  // seconds in a month  (4 weeks)
   "week"   => 604800,   // seconds in a week   (7 days)
   "day"    => 86400,    // seconds in a day    (24 hours)
   "hour"   => 3600,     // seconds in an hour  (60 minutes)  
   "minute" => 60,       // seconds in a minute (60 seconds)
   "second" => 1         // 1 second
  );

  $diff = abs($from - $to);
  $suffix = (($from > $to) ? ("left") : ("old"));

  foreach($units as $unit => $mult)
   if($diff >= $mult)
   {
    $and = (($mult != 1) ? ("") : ("and "));
    $output .= ", ".$and.intval($diff / $mult)." ".$unit.((intval($diff / $mult) == 1) ? ("") : ("s"));
    $diff -= intval($diff / $mult) * $mult;
   }
  $output .= " ".$suffix;
  $output = substr($output, strlen(", "));

  return $output;
 }

Magento 1.9 : Change page layout from controller

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

Replace

$this->loadLayout();

with

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

Different Sidebar for wordpress pages

Often one needs different sidebars for different pages in our wordpress coding. This can be implemented using the below mentioned code. The logic used here is that we get the post id and assign sidebar based on their page or post id's.

We have to adjust the below code in our wordpress sidebar.

global $id;
$post_id_current = get_post($id,ARRAY_A);
$post_parent = $post_id_current['post_parent'];
if($post_parent!='')
{
$my_id=$post_parent;
}
else
{
$my_id=$id;
} 

if($my_id!==4 )
{
 if ( !function_exists('dynamic_sidebar')

|| !dynamic_sidebar('sidebar2') ) : endif; 

}
else
{
 if ( !function_exists('dynamic_sidebar')

|| !dynamic_sidebar('sidebar1') ) :  endif; 
}

Why we use Antivirus?

Many users think that we can get viruses by downloading files,visiting wrong websites and clicking irresponsible things.It's true-this is how we pick viruses, but it is not the only way we pick up viruses,but it is not the only way viruses spread out.Our computer sometime may be infected just from visiting a website or by putting some other external devices e.g.U.S.B,Harddisk etc.

In the leading world of globalisation people trust on computers and internet to send,receive and manage their valuable informations.The term protection is prior word which comes to their mind when using interne, as the informations sent over network has many risks from the devil malwares who are responsible for hampering the information on internet.So it is important for the user to protect their computers from risk.

One of the best solution to this problem is antivirus.An antivirus programs protects your computer from the viruses by identifying and removing it.Now these days antivivirus more often comes with firewall packages that blocks the unwanted things and ptotects your computer.Antivirus automatically scans your files downloaded from the web,email attachments and all types of removable cables inserted in the computer.It also removes malicious .malwares like viruses.Thus making you to feel free to send all your informations.

To prevent our system from the unwanted malware or viruses,we need a software that is know as antivirus.It is used to prevent,detect and remove malicious computer viruses from your computer.Software described viruses from computer.Software described as antivirus also works against different types of malware e.g rootkit,trojan horses,worms and spywares etc.

Updating the antivirus programs regularly is important because it will download an new virus definitation that have been added since last update.

Lamp install on Ubuntu with few clicks

Easiest way to install Lamp Server. I have found after googling for two hours. I thought to share with you so you can also get benefit from it.

sudo apt-get install tasksel 
sudo tasksel install lamp-server 

After you will be prompted to enter mysql root password . Enter the root password for Mysql and press enter. It will install most rexommended php modules.

If you want to install phpmyadmin run below command:

sudo apt-get install libapache2-mod-auth-mysql php5-mysql phpmyadmin

SELECT query in mysql? How can we use SELECT command in my sql?


Select Query in MySQL


SELECT statement use to select data from a database.
Syntex:-
1) If we have select few specific fields from table.
Select coulmn_name1,coulmn_name2 from table_name;
2) If we have to select all records from table.
 
select * from  table_name;
Example
If we have a user table in database:
U_id Uname Mobile City
1 Raj RAJPHONE Ajmer
2 Ravi RAVIPHONE Jaipur
3 Vijay VIJAYPHONE Alwar
Example to :- Select Columns
SELECT Uname,city FROM user;     
Output:
U_id Uname City
1 Raj Ajmer
2 Ravi Jaipur
3 Vijay Alwar
Example to :- Select *
SELECT * FROM user; 
Output:
U_id Uname Mobile City
1 Raj RAJPHONE Ajmer
2 Ravi RAVIPHONE Jaipur
3 Vijay VIJAYPHONE Alwar
Example to :- Select Where
If we have to SELECT specific data from a user table Where city is Ajmer.
SELECT Uname FROM user WHERE city='Ajmer';     
Output:
Uname
Raj

Difference Between Delete , Drop and Truncate command in sql

Delete command

The DELETE command is used to remove rows from a table. A WHERE clause can be used to only remove some rows. If no WHERE condition is specified, all rows will be removed.

Example:

101 Id is deleted in user table

Delete from user where id='101'; 

delete all records from user table

 
Delete * from user ;

The DROP command removes a table from the database. All the tables' rows, indexes and privileges will also be removed.the operation cannot be rolled back.

Example:

user table removed from a database

Drop table user; 

Truncate command

TRUNCATE removes all rows from a table,not a whole table from a database. The operation cannot be rolled back.

Example:

all rows delete from a user table not a table delete

truncate table user; 

What is a trigger in SQL and how can use in SQL?

Trigger In MySQL
Database triggers are SQL statements storing in the database catalog. Once a trigger is activated by database events such as UPDATE, DELETE or INSERT, it will execute either before or after the event that initiated it.
A trigger is a SQL procedure that initiates an action when an event (INSERT, DELETE or UPDATE) occurs.
Syntex:-
CREATE TRIGGER trigger_name trigger_time trigger_event ON tbl_name FOR EACH ROW trigger_body
If We want edit or modify the trigger,We need click on structure menu in phpmyadmin Then click on details link.
trigger_time:
trigger_time is the trigger action time. It can be BEFORE or AFTER to indicate that the trigger activates before or after each row to be modified.
trigger_event:
trigger_event indicates the kind of statement that activates the trigger. The trigger_event can be one of the following:
1. insert query
2. update query
3. delete query
Example:-
delimiter $$
CREATE TRIGGER Employee_Trigger
AFTER insert ON employee
FOR EACH ROW
BEGIN
insert into employee_log values(new.id, new.first_name,
new.last_name);
END$$ 

What is DBMS, RDBMS and MySQL?


What is DBMS?


  • A database management system (DBMS) is a system, usually automated and computerized, used to manage any collection of normalized data.
  • The DBMS manages storage and access to the data, and provides a query language to specify actions associated with the data. The standard query language is SQL.
  • A DBMS generally provides a client application that can be used to directly manipulate the data, as well as a programmable interface. MySQL provides a set of command line clients, as well as a program interface.

What is RDBMS ?


  • Information is stored in tables. Tables store information about entities.
  • Entities have characteristics called attributes.
  • Each row in a table represents a single entity Each row is a set of attribute values Every row must be unique, identified by a key.
  • Relationships --associations among the data values are stored

PHP and MySQL ?


  • MySQL is a database server
  • MySQL is ideal for both small and large applications
  • MySQL supports standard SQL
  • MySQL is free to download and use
PHP + MySQL ("PHP combined with MySQL are cross-platform (means that you can develop in Windows and serve on a Unix platform)")

MySql- IN and BETWEEN operators in MySql


BETWEEN in MySQL


BETWEEN Operators are used to select a values within a range or scope .
Syntax:
Select coulmns_names from table_name WHERE coulmn_name BETWEEN value1 AND value2;
Example:
For below table structure:
p_id pro_name price
1 Samsung 100
2 Reliance 80
3 Vodafone 90
4 Idea 85
Example query for BETWEEN
SELECT * from product WHERE price BETWEEN  80 AND 90;  
Output
P_id Pro_name Price
2 Reliance 80
3 Vodafone 90
4 Idea 85

IN operators in MySQL


IN operators are use to assign multipal values and select data on behalf.
Select coulmns_names from table_name WHERE coulmn_name IN (value1,value2......); 
Example:
Below is a user table:
U_id Uname Mobile City
1 Raj UMOBILE1 Ajmer
2 Ravi UMOBILE2 Jaipur
3 Vijay UMOBILE3 Alwar
4 Pawan UMOBILE4 Jaipur
Example query for IN
SELECT * FROM user WHERE city IN('Ajmer','Jaipur');  
Output
U_id Uname Mobile City
1 Raj UMOBILE1 Ajmer
2 Ravi UMOBILE2 Jaipur
4 pawan UMOBILE4 Jaipur

Magento 1.9 - Customer attribute values by attribute ID

If attribute ID = 161, below is the simple code to get option ids and values for the attribute ID.

$valuesCollection = Mage::getResourceModel('eav/entity_attribute_option_collection')
->setAttributeFilter(161)
->load();


foreach ($valuesCollection as $item) {

$attr = Mage::getModel('eav/entity_attribute_option')
->getCollection()->setStoreFilter()
->join('attribute','attribute.attribute_id=main_table.attribute_id', 'attribute_code')
->addFieldToFilter('main_table.option_id',array('eq'=>$item->getId()))->getFirstItem();
$procategorydata= $attr->getData();  

 echo 'Option ID: ';
 echo $procategorydata['option_id'];
 echo 'Value:';     
 echo $procategorydata['value'];     
 echo '======';

}

PHP- set timezone and get timezone in php

Below are the easy examples to set timezone and get timezone in php

1) Set timezone :-

 echo date_default_timezone_set("Asia/Kolkata"); 

2) Get timezone :-

  echo date_default_timezone_get(); 

Magento 1.9- How to import product images from external url in magento

Magento- How to import product images from external url in magento

In magento sometimes we need to import products and we don't have access to images.
We need to use image urls from external sites.
Click Here to know more how to achieve this.

Magento 1.9 - get all subcategories of parent category

1) Parent category

//Parent category 
$parentCategoryId = 107;
$cat = Mage::getModel('catalog/category')->load($parentCategoryId);
$subcats = $cat->getChildren();

2) Get 1 Level sub category of Parent category.

//Get 1 Level sub category of Parent category
foreach(explode(',',$subcats) as $subCatid){
  $_category = Mage::getModel('catalog/category')->load($subCatid);
  if($_category->getIsActive()) {
    echo '';
  }
}

3) Get 2 Level sub category of Parent sub category.


// Get 2 Level sub category of Parent sub category

foreach(explode(',',$subcats) as $subCatid)
{
  $_category = Mage::getModel('catalog/category')->load($subCatid);
  if($_category->getIsActive()) {
    echo '';
  }
}

4) Get 3 Level sub sub category of Parent sub sub category

// Get 3 Level sub sub category of Parent sub sub category

foreach(explode(',',$subcats) as $subCatid)
{
  $_category = Mage::getModel('catalog/category')->load($subCatid);
  if($_category->getIsActive()) {
    echo '';
  }
}


 // $sub_subCatid this is sub category id . means if you want 4 level than it will take 3 level subcategory Id.

 $sub_sub_cat = Mage::getModel('catalog/category')->load($sub_subCatid);
              $sub_sub_subcats = $sub_sub_cat->getChildren();
              foreach(explode(',',$sub_sub_subcats) as $sub_sub_subCatid)
              {
                $_sub_sub_category = Mage::getModel('catalog/category')->load($sub_sub_subCatid);
                if($_sub_sub_category->getIsActive()) {
                    echo '
  • getName().'" category">'.$_sub_sub_category->getName().'
  • '; } }

    Wordpress- Plugin to fix SSL Insecure Content Fixer

    SSL Insecure Content Fixer 

    It is very good plugin to resolve the SSL Insecure Content issue.


    SSH- Tool to access the files with SSH credentials

    Download Bitvise SSH Client   is the best tool to access the files with SSH credentials.

    Wordpress- WP Force SSL Plugin

    This plugin helps you redirect HTTP traffic to HTTPS without the need of touching any code.

    We can see the details, going through the link WP Force SSL

    PHP - simplest way to detect a mobile device

    Below is the PHP code to detect a mobile device. It is working for me and very useful and easy to use.

    $useragent=$_SERVER['HTTP_USER_AGENT'];
    
    if(preg_match('/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i',$useragent)||preg_match('/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene
    
    |gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a
    
    |jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt
    
    |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)
    
    |mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)
    
    |wmlb|wonu|x700|yas\-|your|zeto|zte\-/i',substr($useragent,0,4))){
      
      echo 'I am mobile device condition.';
    
    }echo{
    
      echo 'I am not mobile device condition.';
    }
    
    

    Magento 1.9- How to check user login or not in magento

    How to check user login or not in magento.

    Below is the simple code to check user login or not in magento.

    
    $myStatus = Mage::getSingleton('customer/session')->isLoggedIn();
    if($myStatus):
      echo 'Loogedin';
    else:
       echo 'Not Loogedin';
    endif;
    

    Magento 1.9 - update handle example in magento

    Below are the example for update handle.

    1) For One Column

    
    

    2) For Two Column left

    
    

    3) For Two Column right

    
    

    Magento 1.9 - Get store Admin Email Address and Name

    Fetch sender email Admin

    $from_email = Mage::getStoreConfig('trans_email/ident_general/email'); //fetch sender email Admin
    

    Fetch sender name Admin

    $from_name = Mage::getStoreConfig('trans_email/ident_general/name'); //fetch sender name Admin
    

    Magento 1.9 - Get all options of a dropdown or multiselect attribute in magento

    Below is the example code.

    this may be any attribute code

    $arg_attribute = "manufacturer";
    

    Object of attribute model

    $attribute_model = Mage::getModel('eav/entity_attribute'); 
    

    Object of attribute options model

    $attribute_options_model= Mage::getModel('eav/entity_attribute_source_table') ;
    $attribute_code = $attribute_model->getIdByCode('catalog_product', $arg_attribute); 
    $attribute = $attribute_model->load($attribute_code); 
    $attribute_table =$attribute_options_model->setAttribute($attribute);
    

    Getting all options

    $options = $attribute_options_model->getAllOptions(false);
    

    Printing all options of particular attribute

    print_r($options); 
    

    Below is comple code

    //this may be any attribute code
    $arg_attribute = "manufacturer";
    
    //Object of attribute model
    $attribute_model = Mage::getModel('eav/entity_attribute'); 
    
    //Object of attribute options model
    $attribute_options_model= Mage::getModel('eav/entity_attribute_source_table') ;
    $attribute_code = $attribute_model->getIdByCode('catalog_product', $arg_attribute); 
    $attribute = $attribute_model->load($attribute_code); 
    $attribute_table =$attribute_options_model->setAttribute($attribute);
    
    
    //Getting all options
    $options = $attribute_options_model->getAllOptions(false);
    
    //Printing all options of particular attribute
    print_r($options); 
    

    Magento 1.9 -How to call a PHTML file within a CMS page Magento

    Below is the simple example with steps.

    1) create a file like review.phtml

    2) and save in catalog/product/review.phtml

    3)create a cms page and insert following line in content field

    {{block type="core/template" name="review" template="catalog/product/review.phtml"}}
    

    Hope this article will be usefule for you.

    How can we do "Responsively Rearrange/Reorder DIV elements" using CSS?

    It is a small, but very useful trick that can help us. when we want to change order of elements on the page on mobile devices. Of course, it may be used for any other purposes.

    First of all, we have to specify a container:

    Secondly, we have to define inner elements with appropriate classes.

    DIV #1
    DIV #2

    As we can see the default order is following: DIV #1 and then DIV #2 But how can we change this order on mobile devices? It is very simple. Add for each element class for order and define its as following.

    CSS:

    @media screen and (max-width: 786px) {
     .order_container_main { display: flex; flex-flow: column; }
     .order4 { order: 4; }
     .order3 { order: 3; }
     .order2 { order: 2; }
     .order1 { order: 1; }
    }
    

    HTML:

    DIV #1
    DIV #2

    Now in mobile the order of elements will be following: DIV #2 and then DIV #1

    PHP- Send email with attachment file in php

    Below is the HTML and PHP code to Send email with attachment file.

    HTML CODE

    PHP CODE

    function mail_attachment($filename, $path, $mailto, $from_mail, $from_name, $replyto, $subject, $message) {
        $file = $path.$filename;
        $file_size = filesize($file);
        $handle = fopen($file, "r");
        $content = fread($handle, $file_size);
        fclose($handle);
        $content = chunk_split(base64_encode($content));
        $uid = md5(uniqid(time()));
        $name = basename($file);
        $header = "From: ".$from_name." <".$from_mail.">\r\n";
        $header .= "Reply-To: ".$replyto."\r\n";
        $header .= "MIME-Version: 1.0\r\n";
        $header .= "Content-Type: multipart/mixed; boundary=\"".$uid."\"\r\n\r\n";
        $header .= "This is a multi-part message in MIME format.\r\n";
        $header .= "--".$uid."\r\n";
        $header .= "Content-type:text/plain; charset=iso-8859-1\r\n";
        $header .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
        $header .= $message."\r\n\r\n";
        $header .= "--".$uid."\r\n";
        $header .= "Content-Type: application/octet-stream; name=\"".$filename."\"\r\n";
        $header .= "Content-Transfer-Encoding: base64\r\n";
        $header .= "Content-Disposition: attachment; filename=\"".$filename."\"\r\n\r\n";
        $header .= $content."\r\n\r\n";
        $header .= "--".$uid."--";
        if (mail($mailto, $subject, "", $header)) {
            echo "mail send ... Successfully";
        } else {
            echo "ERROR!";
        }
    }
    if(isset($_POST['sub']))
    {
    
    $filename = $_FILES['attc']['name'];
    move_uploaded_file($_FILES['attc']['tmp_name'],"file_attached/".$filename);
    $path = "file_attached/";
    $mailto = "your-email@gmail.com";
    $from_mail = "from@gmail.com";
    $from_name = "from_name";
    $replyto = "reply@gmail.com";
    $subject = "new testing";
    $message = "Please find attached file";
    echo mail_attachment($filename, $path, $mailto, $from_mail, $from_name, $replyto, $subject, $message);
    }
    

    Can I programmatically login a user without a password?

    Question:
    Can I programmatically login a user without a password? I'm manually creating users programmatically, and I want to sign in the newly created user. WP makes it easy to access the hashed password, but not the plaintext version. Is there a way to use wp_signon() without the plaintext password?

    Answer:
    The following code does the job for automatic login, without any password!

    // Automatic login //
    $username = "Admin";
    $user = get_user_by('login', $username );
    
    // Redirect URL //
    if ( !is_wp_error( $user ) )
    {
        wp_clear_auth_cookie();
        wp_set_current_user ( $user->ID );
        wp_set_auth_cookie  ( $user->ID );
    
        $redirect_to = user_admin_url();
        wp_safe_redirect( $redirect_to );
        exit();
    }
    

    What is Z-index property in CSS ?

    The z-index property in CSS controls the vertical position order of an elements.
    An element with greater position order is always use in front & lower in back.

    Z-index property:
    z-index property is use always greatest position order of an element.

    Syntax:-
    z-index: "position-order";
     
    Syntax Example:-
    z-index: 1;
     
    Example: HTML & CSS code
    Z-index:2
    Z-index:3
    Z-index:1
    Output of Above the Code is as below.

    Magento 1.9 - Magento Interview Questions and Answers

    Twelve important questions and answers in Magneto .

    Q 1) What is the difference between

    Mage::getSingletone();
    and
    Mage::getModel();
    in Magento.

    Ans)

    Mage::getSingletone();
    always finds for an existing object if not then create that a new object but
    Mage::getModel();
    always creates a new object.

    Q 2) Why Magento use EAV database model ?

    Ans) In EAV database model, data are stored in different smaller tables rather than storing in a single table. product name is stored in catalog_product_entity_varchar tableproduct id is stored in catalog_product_entity_int tableproduct price is stored in catalog_product_entity_decimal tableMagento Use EAV database model for easy upgrade and development as this model gives more flexibility to play with data and attributes.

    Q 3) How to upgrade to the latest version using Magento Connect?

    Ans) Upgrading Magento to the latest version is a fairly simple task. Copy and Paste this key magento-core/Mage_All_Latest VIA Magento Connect where it states Paste extension key to install:. This will upgrade Magento to the newest version.

    Q 4) Explain about the Modules of Magento?

    Ans) Magento supports installation of modules through a web-based interface accessible through the administration area of a Magento installation. Modules are hosted on the Magento eCommerce website as a PEAR server. Any community member can upload a module through the website and is made available once confirmed by a member of the Magento team. Modules are installed by entering a module key, available on the module page, into the web based interface.

    There are three categories of modules hosted on Magento Connect:

    • Core Modules
    • Community Modules
    • Commercial Modules

    Core and Community modules can be installed via the administration area. Commercial module pages provide price information and a link to an external website.

    Q 5) How to include CMS block in template file(.phtml)?

    Ans) Access block’s content from .phtml template file by :

    echo $this->getLayout()->createBlock('cms/block')->setBlockId('static_block_id')->toHTML();

    Q 6) How to get the Total Price of items currently in the Cart?

    Ans)

     helper('checkout')->formatPrice(Mage::getSingleton('checkout/cart')->getQuote()->getGrandTotal()); 

    Q 7) How to set different themes for logged in users?

    Ans)

     if(Mage::getSingleton('customer/session')->isLoggedIn()):
    Mage::getDesign()->setPackageName('package_name')->setTheme(‘themename’);
    endif;

    Q 8) How to create magento custom module?

    Ans) Steps to create custom magento module:

    Namespace : Zag

    Module Name : Mymodule

    1. Create directory Mymodule in app/code/local/Zag
    2. Create Block, controllers, etc, Module directories. Create controller, block and module file as required.
    3. Create module configuration file (app/code/local/Zag/Mymodule/etc/config.xml).
    4. Create xml file (app/etc/modules/Zag_ Mymodule.xml)to enable/disable module and tell magento system from which code pool that module will be taken.

    Q 9) How to set different themes for each store?

    Ans) Go to :

    System>Designs

    Then, add new design change or edit existing. You can select Store and Custom Design.

    Q 10) How to make product’s custom attribute searchable in advance search?

    Ans) Go to :

    Catalog > Attributes > Manage Attributes

    Edit the attribute and select “Yes” for Use in Advanced Search.

    Q 11) How to run custom MySql query in Magento ?

    Ans) Below is the simple code. We can easily understand this.

     $db = Mage::getSingleton('core/resource')->getConnection('core_write'); 
    $result=$db->query("SELECT * FROM PCDSTable"); 

    Q 12) What is the difference between

    Mage::getSingletone(); 
    and
    Mage::getModel();
    in Magento?

    Ans)

     Mage::getSingletone();
    always finds for an existing object if not then create that a new object but
    Mage::getModel();
    always creates a new object.

    MySQL INSERT if not exist (do not insert if exist)

    Question:
    How can I insert into a row if the pair does not exist?

    Answer:
    To get the solution, we have just to follow the below simple steps.

    1) Can you add a UNIQUE constraint on (myid, theirid)? If yes, add this constraint and use:

    INSERT INTO mytable (myid, theirid) 
      VALUES (5, 1) ;
    

    and ignore the produce warnings (or replace the above with INSERT IGNORE)

    2) If you can't add such a constraint (e.g. you sometimes want to allow such duplicates and other times you don't), you can use this:

    INSERT INTO mytable (myid, theirid) 
    SELECT 5, 1 
    FROM dual 
    WHERE NOT EXISTS
     ( SELECT *
       FROM mytable
       WHERE myid = 5
      AND theirid = 1
     ) ; 
    

    How can we insert contact form 7 data/email in another table in wordpress?

    If we want to save the form to a custom table in our WP database and If we have to insert email in wp_newsletter table if email is not exist in table.

    Also The email should still be sent.

    For this we just have to use the below code in our theme's function.php file:

    
    /*
     insert email in newsletter after submitting contact form 7
    */
    add_action("wpcf7_before_send_mail", "wpcf7_do_something_else");  
    function wpcf7_do_something_else($cf7) {
        $wpcf = WPCF7_ContactForm::get_current();
     
     $submission = WPCF7_Submission::get_instance();
     $posted_data = $submission->get_posted_data();
        $youremail = $posted_data['your-email'];  //If  your-email is email field name.
        // if we have to insert email in wp_newsletter table if email is not exist in table.
      global $wpdb; 
      $query= "INSERT INTO wp_newsletter (email,status) 
         SELECT '$youremail','C'
         FROM dual 
         WHERE NOT EXISTS
         ( SELECT *
           FROM wp_newsletter
           WHERE email = '$youremail'
           AND status= 'C'
         ) ; ";
      
      $wpdb->query($wpdb->prepare($query));
     /*
     mail("amu02.aftab@gmail.com","My subject",$query); 
        */ 
     
        return $wpcf;
    }
    

    MVC- How can we insert the data in database using MVC in PHP?

    MVC(Model View Controller) have.

    1) Model class

    2) View (HTML/css)

    3) Controller class

    MVC-View file

    What we want to display on the the Browser, for example HTML,CSS,JavaScript etc. in view file.

    First of all we have to created a form that are describes below and after that include controller class and get the request of a submit button and finally pass the data in a function.

    include("controller.php");
    // assign the object for controller class
    $obj = new controller(); 
    if(isset($_REQUEST('submit'))){
    $n=$_REQUEST['name'];
    $p=$_REQUEST['pass'];
    // Pass the data in insert function
    $obj->insert($n,$p); 
    header("location:view.php");
    }
    

    Example: Below is our form. When we will enter value in name and Password and click on submit button then work above code. In this case we will get request the value of name and password.

    name
    password

    MVC - Controller

    Controller is the mediator of model & View that are connect the each other .

    include("model.php");
    class controller{
     public function insert($n,$p){
      $obj = new model();
      $obj->insert($n,$p);
     }
    }
    

    MVC - Model

    Model is the database class that are interact with the database and response via controller on the view

    class model{
     public function model(){
      mysql_connect("localhost","root","");
      mysql_select_db("mvc");
     }
     public function insert($n,$p){
      $ins ="insert into user (name,pass) values('$n','$p')";
      $rs= mysql_query($ins);
     }
    }
    

    PHP- How can we access private method outside the class?

    If we have to access private method for out side the class then we can get it easily using below simple example:

    Class Stack
    {
        private function myPrivateMethod()
        {
            return 'I am out from private method.';
        }
    }
    
    $stack = new Stack();
    
    $reflection_class = new ReflectionClass($stack);
    $private_method = $reflection_class->getMethod('myPrivateMethod');
    $private_method->setAccessible(true);
    echo $private_method->invoke($stack);
    
    

    Output :

     I am out from private method.
    

    n the above example we have made object of ReflectionClass and set the true in setAccessible() method. ReflectionClass is reporting information about a class

    Clear cart in woocommerce, how can we empty cart in woocommerce wordpress?

    To remove all cart products

    Include below code in the cart.php:

    
    
    
    

    We can easily remove whole cart product by adding above code.

    Laravel - How can we install laravel using composer ?

    Below is the easy steps-

    Step 1. Go in the directory

    var/www/html/
    

    Step 2. Install composer

    we can install composer in the current directory, run the following script in your terminal. you can alos visit the folowing link https://getcomposer.org/download/

    cmd1 :

    php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
    

    cmd2 :

    php -r "if (hash_file('SHA384', 'composer-setup.php') === '544e09ee996cdf60ece3804abc52599c22b1f40f4323403c44d44fdfdd586475ca9813a858088ffbc1f233e9b180f061') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"
    

    cmd3 :

    php composer-setup.php
    

    cmd4 :

    php -r "unlink('composer-setup.php');"
    

    Or

    composer global require "laravel/installer"
    

    Step 3.

    composer create-project --prefer-dist laravel/laravel {directory name here}
    

    Eg. composer create-project --prefer-dist laravel/laravel testlaravel

    Step 4.

    Check created folder in current directory.

    var/www/html/testlaravel
    

    Step 5.

    Hit the url : http://localhost/testlaravel/public/

    Step 6.

    Have Fun :)

    PHP- How can we get second highest number from a numeric array?

    We can easily find second highest number from array.

    Process of find the second largest number are in below simple steps

    1. Create a numeric array like :

    $array = array('200', '15','69','122','50','201','300');

    2. Create two variable $first and $second and assign 0 value

    3. Start for loop and add condition

    for($i=0; $i < count($array); $i++)
    {
     if($array[$i] > $first){
       $second = $first;
       $first = $array[$i];
     }
    }
    

    Complete code

     $array = array('200', '15','69','122','50','201','300');
     $first = 0;
     $second = 0;
    
     for($i=0; $i < count($array); $i++)
     {
        if($array[$i] > $first){
          $second = $first;
          $first = $array[$i];
        }
     }
     echo "Highest Number=".$first;
     echo "
    "; echo "Second Highest Number=".$second;

    PHP- get specific days from month

    How we can get specific days from month within given date range in PHP?

    If you are facing problem with "to get specific days from two months". I have added below solution that are working fine for me. Hope this will useful for you.

    $cdate = date('d-m-Y'); //this is current date
    $date = strtotime('+2 months'); //this is date after two months.
    $nextDate = date('d-m-Y', $date);
    
    $dates = dateRange($cdate, $nextDate);
    function dateRange($begin, $end, $interval = null){
        $begin = new DateTime($begin);
        $end = new DateTime($end);
        // Because DatePeriod does not  the last date specified.
        $end = $end->modify('+1 day');
        $interval = new DateInterval($interval ? $interval : 'P1D');
        return iterator_to_array(new DatePeriod($begin, $interval, $end));
    }
    
    $days = array_filter($dates, function ($date) {
        $day = $date->format("l");
        return $day === 'Tuesday' || $day === 'Thursday' || $day === 'Sunday';
    });
    
    $arrayDays = array();
    foreach ($days as $date) {
        $arrayDays[] = $date->format("d-m-Y");
    }
    
    //print Output
    print_r($arrayDays);
    

    This is show Tuesday, Thursday, Sunday date from 2 months.