Monday 16 December 2013

Wordpress login redirect on magento login

When user click on wordpress login it will be redirected on magento login page. After successfully login it will be redirected to wordpress site.

Add function in wp-content/themes/themefolder/functions.php

    <?php
    // For login page
    function redirect_login_page(){
       $page_viewed = basename($_SERVER['REQUEST_URI']);
       $redirect_link = base64_encode($_GET['redirect_to']);
       $home_url = base64_encode( site_url() );
        if( $page_viewed == "wp-login.php") {
          // And away they go...
           $login_page  = 'store url/customer/account/login/referer/'.$home_url; // Store url is your magento site url
           wp_redirect($login_page);
         }
         // For redirection url
         if($_GET['redirect_to'] != '') {
          $login_page  = 'store url/customer/account/login/referer/'.$redirect_link; // Store url is your magento site url
              // This condition is checked for Admin user.
              if( $_GET['redirect_to'] != 'website url/wp-admin/') {  // website url is your website site url
                 wp_redirect($login_page);
              }
         }
    }
    add_action('init','redirect_login_page');
   
    // For logout page
    function redirect_logoutpage()
    {
       $logout_page  = 'store url/customer/account/logout/'; // Store url is your magento site url
       $redirect_link = base64_encode($_GET['redirect_to']);
         if($_GET['loggedout'] || $_GET['action'] == 'logout') {
              if( $_GET['redirect_to'] != 'website url/wp-admin/') { // website url is your website site url
                 wp_redirect($logout_page);
              }
         }
    }
    add_action('init','redirect_logoutpage');
    ?>

Synchronize magento customer and wordpress user

When user login in store(magento site) it will be automatically login in website(wordpress site). If the user is registered both site with same user name and password. And also user is logout in store it will be automatically logout from website.
Please see below steps:

  • Install extension http://www.magentocommerce.com/magento-connect/magento-wordpress-integration.html in your store using connect manager.
  • Setup your website and connect with Store.
  • Now you will be able automatically login with store admin panel to website admin panel.
  • For merge customer and user login you have to changes in code like.

Add this code in index.php file which is located in root folder of store files.

    <?php
    if ( strpos($_SERVER['REQUEST_URI'], 'index.php/admin') === FALSE )
    {
        define('WP_USE_THEMES', false);
        require_once('/wp-load.php'); // Add Absolute path of wp-load.php
    }
    if (!function_exists('__')) {
        function __() {
        return Mage::app()->getTranslator()->translate(func_get_args());
        }
    }
    ?>

Then after go to /app/code/core/Mage/Core/functions.php and find
   
    <?php
    function __()
    {
        return Mage::app()->getTranslator()->translate(func_get_args());
    }
    ?>
   
And replace this

    <?php
    if (!function_exists('__')) {
        function __()
        {
            return Mage::app()->getTranslator()->translate(func_get_args());
        }
    }
    ?>
   
Then after add this function in website theme's functions.php
wp-content/themes/themefolder/functions.php

    <?php
    function login_with_email_address($username) {
        $user = get_user_by_email($username);
        if(!empty($user->user_login))
        $username = $user->user_login;
        return $username;
    }
    add_action('wp_authenticate','login_with_email_address');
    ?>
   
Then after copy this file  /app/code/core/Mage/Customer/controllers/AccountController.php and put in  /app/code/local/Mage/Customer/controllers/AccountController.php  find loginPostAction and replace with below code.

    <?php
    /**
    * Login post action
    */
    public function loginPostAction()
    {
        if ($this->_getSession()->isLoggedIn()) {
            $this->_redirect('*/*/');
            return;
        }
        $session = $this->_getSession();

        if ($this->getRequest()->isPost()) {
            $login = $this->getRequest()->getPost('login');
            if (!empty($login['username']) && !empty($login['password'])) {
                try {
                    $session->login($login['username'], $login['password']);
                    $user = login_with_email_address($login['username']);
                    $creds = array();
                    $creds['user_login'] = $login['username'];
                    $creds['user_password'] = $login['password'];
                    $creds['remember'] = true;
                    $user = wp_signon( $creds, false );
                    if ( is_wp_error($user) ) :
                        echo $user->get_error_message();
                    endif;
                     wp_set_current_user($user->ID);
                     wp_set_auth_cookie($user->ID);
                    if ($session->getCustomer()->getIsJustConfirmed()) {
                        $this->_welcomeCustomer($session->getCustomer(), true);
                    }
                } catch (Mage_Core_Exception $e) {
                    switch ($e->getCode()) {
                        case Mage_Customer_Model_Customer::EXCEPTION_EMAIL_NOT_CONFIRMED:
                            $value = Mage::helper('customer')->getEmailConfirmationUrl($login['username']);
                            $message = Mage::helper('customer')->__('This account is not confirmed. <a href="%s">Click here</a> to resend confirmation email.', $value);
                            break;
                        case Mage_Customer_Model_Customer::EXCEPTION_INVALID_EMAIL_OR_PASSWORD:
                            $message = $e->getMessage();
                            break;
                        default:
                            $message = $e->getMessage();
                    }
                    $session->addError($message);
                    $session->setUsername($login['username']);
                } catch (Exception $e) {
                    // Mage::logException($e); // PA DSS violation: this exception log can disclose customer password
                }
            } else {
                $session->addError($this->__('Login and password are required.'));
            }
        }
        $this->_loginPostRedirect();
    }
    ?>
   
Then after find logoutAction replace with below code.

    <?php
    public function logoutAction()
    {
        $this->_getSession()->logout()
            ->setBeforeAuthUrl(Mage::getUrl());
        wp_logout();
        $this->_redirect('*/*/logoutSuccess');
    }
    ?>
   
Now you can sucessfully login with store to automatically login with website.

Thursday 25 July 2013

Magento Admin panel login not working in localhost


Step 1: Copy varien.php file from app\code\core\Mage\Core\Model\Session\Abstract folder
Step 2: Paste into app\code\local\Mage\Core\Model\Session\Abstract folder. Before you paste the file you need to create the folders as specified in this path such as \Mage\Core\Model\Session\Abstract.
Step3: Open varien.php in your favorite editor.
Step4: Find line no 96 and the code will be like



if (isset($cookieParams['domain'])) {
$cookieParams['domain'] = $cookie->getDomain();
}


     and replace with

if ((isset($cookieParams['domain'])) && !in_array("127.0.0.1", self::getValidatorData())) {
$cookieParams['domain'] = $cookie->getDomain();
}


Step 5: That’s it. Now you will be able to login Magento admin panel.

Monday 22 July 2013

Magento Admin panel login not working in Chrome

Go to /app/code/core/Mage/Core/Model/Session/Abstract/Varien.php

Find line no 85 and the code will be like

       // session cookie params

       $cookieParams = array(
           'lifetime' => $cookie->getLifetime(),
           'path'     => $cookie->getPath(),
           'domain'   => $cookie->getConfigDomain(),
           'secure'   => $cookie->isSecure(),
           'httponly' => $cookie->getHttponly()
       );

and replace with  

       $cookieParams = array(
           'lifetime' => $cookie->getLifetime(),
           'path'     => $cookie->getPath(),
           'domain'   => $cookie->getConfigDomain(),
           'secure'   => $cookie->isSecure(),
         //  'httponly' => $cookie->getHttponly()
       );

That’s it. Now you will be able to login Magento admin panel.

Tuesday 25 June 2013

Get all Product type's price show in homepage in magento

Get Simple Product Price in Homepage

<?php echo $_product->getFormatedprice(); ?>

Get Group Product Price in Homepage


<?php  
    $aProductIds = $_product->getTypeInstance()->getChildrenIds($_productl->getId());
    $prices = array();
    foreach ($aProductIds as $ids) {
           foreach ($ids as $id) {
                  $aProduct = Mage::getModel('catalog/product')->load($id);
                  $prices[] = $aProduct->getPriceModel()->getPrice($aProduct);
            }
     }
     //krsort($prices);
     asort($prices);
     echo $_product->setPrice(array_shift($prices));
   ?>


Get Bundle Product (Maximum and Minimum) Price in Homepage


      $_product_id            = $_product->getId();  //Here bundle Product id


//$return_type  select which you want to get price. If you want to get Max Price, you will add $return_type = ‘max’. And if you want to get minimum Price of product, you will add $return_type = ‘min’


      // highest possible price for this bundle product
      //$return_type            = 'max';
     
            // lowest possible price for this bundle product
       $return_type         = 'min';
     
      $model_catalog_product  = Mage::getModel('catalog/product'); // getting product model
      $_product               = $model_catalog_product->load( $_product_id );
      $TypeInstance           = $_product->getTypeInstance(true);
$Selections             = $TypeInstance->getSelectionsCollection($OptionIds, $_product );
$Options                = $TypeInstance->getOptionsByIds($OptionIds, $_product);
$bundleOptions          = $Options->appendSelections($Selections, true);
     
$minmax_pricevalue  = 0; // to sum them up from 0
     
foreach ($bundleOptions as $bundleOption) {
      if ($bundleOption->getSelections()) {
          $bundleSelections       = $bundleOption->getSelections();
          $pricevalues_array  = array();
          foreach ($bundleSelections as $bundleSelection) {
              $pricevalues_array[] = $bundleSelection->getPrice();
          }
          if ( $return_type == 'max' ) {
              rsort($pricevalues_array); // high to low
          } else {
              sort($pricevalues_array);   // low to high
          }
          // sum up the highest possible or lowest possible price
          $minmax_pricevalue += $pricevalues_array[0];
      }
  }
// echo $minmax_pricevalue;  //Get minimum price value
echo 'As low as '.Mage::helper('core')->currency($minmax_pricevalue, true, false);   //Get minimum price value with store currency.


Get Configurable Product Price in Homepage


$product = Mage::getModel('catalog/product')->load($_product->getId());
//load all children
$childProducts = Mage::getModel('catalog/product_type_configurable')
           ->getUsedProducts(null,$product);
$childPrice = array();
foreach($childProducts as $child){
    $_child = Mage::getModel('catalog/product')->load($child->getId());
    $childPrice[] =  $_child->getPrice();
}
//If you want to minimum price of product use this
echo min($childPrice);


//If you want to maximum price of product use this
echo max($childPrice);

Add Multiple Items in cart in Magento


$product_id = 32;  //Here is first Product id
$warranty_id = 35;  //Here is second Product id
//You can also pass multiple product id.
$someQty = 1; //Here is quantity
//You can add different quantity for different product.


$cart = Mage::getModel("checkout/cart");
$cart->addProduct($product_id, $someQty);
$cart->addProduct($warranty_id, $someQty);
            $cart->save();

Monday 24 June 2013

Get Realted, Upsell, Cross sell Product collection in magento

Get Related Product Collection


$related_product_collection = $_product->getRelatedProductCollection();
$related_product_collection->AddStoreFilter();
foreach($related_product_collection as $pdt)
{
    $pdt_id=$pdt->getId();
    $model_rel = Mage::getModel('catalog/product'); //getting product model
    $_product_rel = $model_rel->load($pdt_id); //getting product object for particular product id
    $rel_name= $_product_rel->getName();
    $rel_price= number_format($_product_rel->getPrice(),2);
    $rel_img_url = $this->helper('catalog/image')->init($_product_rel, 'image')->keepFrame(false)->resize(156,107);   //Image resize code
?>


Get Upsell Product Collection


<?php
$upsell_product_collection = $_product->getUpSellProductCollection();
$upsell_product_collection->AddStoreFilter();
foreach($upsell_product_collection as $pdt)
{
    $pdt_id=$pdt->getId();
    $model_upsell = Mage::getModel('catalog/product');
    $_product_upsell = $model_upsell->load($pdt_id);
    $upsell_name= $_product_upsell->getName();
    $upsell_price= number_format($_product_upsell->getPrice(),2);
    $upsell_img_url = $this->helper('catalog/image')->init($_product_upsell, 'image')->keepFrame(false)->resize(100,100);
?>


Get Cross Sell Product Collection


<?php
$crossselll_product_collection = $_product->getCrossSellProducts(); $crossselll_product_collection>AddStoreFilter();
foreach($crossselll_product_collection as $pdt)
{
    $pdt_id=$pdt->getId();
    $model_crosssell = Mage::getModel('catalog/product');
    $_product_crosssell = $model_crosssell>load($pdt_id);
    $crosssell_name= $_product_crosssell->getName();
    $crosssell_price= number_format($_product_crosssell->getPrice(),2);
    $crosssell_img_url = $this->helper('catalog/image')->init($_product_crosssell, 'image')->keepFrame(false)->resize(100,100);
?>

Get Current Page Detail in magento

Get title
<?=Mage::getSingleton(‘cms/page’)->getTitle()?>
Get Identifier
<? echo Mage::getBlockSingleton(‘cms/page’)->getPage()->getIdentifier()?>
Get Page ID
<? echo Mage::getBlockSingleton(‘cms/page’)->getPage()->getId();  ?>

Friday 24 May 2013

Get Page detail by page id in magento

Get Page tilte


echo Mage::getModel('cms/page')->load(3)->getTitle();  // Here 3 is page id


Get Page content


echo Mage::getModel('cms/page')->load(3)->getContent(); // Here 3 is page id


Get Page Url


echo Mage::helper('cms/page')->getPageUrl(3) ; // Here 3 is page id


Get excerpt


$full_content = Mage::getModel('cms/page')->load(3)->getContent(); // Here 3 is page id
$excerpt = strip_tags(substr($full_content,0,200));  // Here 200 is character length.
echo $excerpt;

Friday 17 May 2013

Get All Product Collection in magento

Get All Product Collection
 
<?php
       $product_collection = Mage::getModel('catalog/product')->getCollection()->setOrder('name', 'asc'); 
      
       //getting the product collection, results are ordered by product name
       
      foreach($product_collection as $_product)
       {
           echo $_product->getId() . "<br />";
       }
?>


Get Limitation product


       <?php
       $limit = 5;
       $starting_from = 0;
       $product_collection = Mage::getModel('catalog/product')->getCollection()->setOrder('name', 'asc'); 
       //getting the product collection, results are ordered by product name

       $product_collection->getSelect()->limit($limit,$starting_from);   
       
       //where $limit will be the number of results we want, $starting_from will be the index of the result set to be considered as starting point (note 0 is the index of first row)
       //this will ouptput 5 records starting from 1rd record

       foreach($product_collection as $_product)
       {
           echo $_product->getName().'<br/>';
           echo $_product->getId() . "<br />";
       }
       ?>


Get Latest Product Collection


       <?php
          $_productCollection = Mage::getResourceModel('reports/product_collection')
                           ->addAttributeToSelect('*')
                           ->setOrder('created_at', 'desc')
                           ->setPage(1, 5);
       ?>
       <h2>Latest Products</h2>
       <?php foreach($_productCollection as $_product) : ?>
        <a href="<?php echo $_product->getProductUrl(); ?>"><?php echo $_product->getName(); ?></a></br>
       <?php endforeach; ?>