Saturday 6 December 2014

Dynamicaly change page title in php

<?php ob_start(); //top of the page.
?>
<title>%TITLE%</title>

<?php 
echo page_title("page title");

function page_title($title) {  //dinamicaly set page title

$buffer=ob_get_contents();
ob_clean();
$buffer=str_replace("%TITLE%",$title,$buffer);
return $buffer;

}
?>

Wednesday 26 November 2014

resize image in php

First you enable following extension in php.ini file  if exist else install php imagick in 
you server :-

set in php.ini file :-

extension=php_imagick.dll


<?php

$thumb = new Imagick();

$thumb->readImage(product_image1);
$thumb->resizeImage(100,100,Imagick::FILTER_LANCZOS,1);
$thumb->writeImage('new100x100.jpeg');


$thumb->readImage(product_image1);
$thumb->resizeImage(200,200,Imagick::FILTER_LANCZOS,1);
$thumb->writeImage('new200x200.jpeg');
$thumb->destroy();

?>

Saturday 22 November 2014

Add calendra in text box jquery

<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.8.3.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>

<script>
var j = jQuery.noConflict();
    j(function() {
        j( "#datepicker" ).datepicker();
    });
</script>

HTML:- <input type="text" id="datepicker" />

form value hold after page redirect in laravel



return Redirect::to('admin/employee/addnew')->withInput()->withErrors($validation);

how to change server php version through htaccess in laravel

paste following code in your root htaccess file :-

AddHandler application/x-httpd-php54 .php
suPHP_ConfigPath /opt/php54/lib

how to define error pages in laravel

First you open app/start/global.php file

find below function :-

App::error(function(Exception $exception, $code)
{
    Log::error($exception);

And last set following condition :-

if ( ! in_array($code,array(401,403,404,500))){
       return;
    }

    $data = array('code'=> $code);

    switch ($code) {

case 401:

         return Response::view('errors.err401', $data, $code); ///set path of app/views/errors/err401.blade.php

       break;     

case 402:

         return Response::view('errors.err402', $data, $code);

       break;      

   case 403:

         return Response::view('errors.err403', $data, $code);

       break;

       case 404:

         return Response::view('errors.err404', $data, $code);

       break;

   }
  
   });

how to use session in laravel

1. save value in session :-
Session::put('key', 'value');

2. get value of session:-

Session::get('key', 'value');

3. remove value of perticuler key :-

Session::forget('key', 'value');

4. Destroy session value :-

Session::flush();

how to call view page in controler in laravel


return View::make('pages.index');  //path :- views/pages/index.blade.php

how to set logout in laravel


 Auth::logout(); //(logout function)

            
  Session::flush(); // if above function give error then user this function

(Destroy all sessions)

Laravel default User login Code

Use following code in your post controller :-


if (Auth::attempt(array('email'=>Input::get('email'), 'password'=>Input::get('password'))))
             {

            return Redirect::to('admin/dashboard')->with('message', 'You are now logged in!');
         }
       
        else {
           
                   return Redirect::to('admin')->with('message', 'Your username/password combination was incorrect');
       
             }

how to check user login or not in laravel

if(Auth::check()){
       
         return View::make('user-login');
       
        }
        else {
        return Redirect::to('notlogin');
        }

get all information of online user in laravel


{{Auth::user()->user_id}},

{{Auth::user()->user_name}}

how to encode password for insert in db in laravel


Hash::make(Input::get('password'));

how to get all validation error message together in laravel

<span>
@foreach($errors->all(':message') as $message)
{{ $message }}
@endforeach
</span>

show validation error messages in view page in laravel

 Following code paste ( after or before) on  you form field where you want show message :-

 @if ($errors->has('fieldname')) <p class="">{{ $errors->first('fieldname') }} @endif

file upload in laravel

 Use this code in your controller :-

$fileName = Input::file('file')->getClientOriginalName();

$destinationPath = base_path().'/public/upload/';

Input::file('file')->move($destinationPath, $fileName);

form in laravel format

{{ Form::open(['url' => '/admin', 'method' => 'post']) }}

{{Form::text('username', null,array('placeholder' => 'Username','class' => 'form-control','id' => 'input-username'))}}

{{Form::password('password', null,array('placeholder' => 'Password','class' => 'form-control','id' => 'input-password'))}}

{{Form::submit('Login', array('name' => 'sub','class' => 'btn btn-primary'))}}

{{ Form::close() }}

controller value pass in view page in laravel

First you pass value in controller :-

return View::make('admin_pages.dashboard')->with('message',$message);

and get this messages on view page :-

<span>@if ($alert = Session::get('message'))
  
        {{ $alert }}
  
@endif </span>

Thursday 20 November 2014

how to set form validation in laravel

 In your controller set this code after form post :-


 $rules = array(
        'categoryname'                => 'required|alpha',
        'childrenacceptjesus'         => 'required|numeric',
        'file'                        => 'required|max:10000',
        'childrengraduated'           => 'required|numeric|max:450',
        'email'                       => 'required|email|unique:users',
        'username'                    => 'required|min:6|unique:users',
        'password'                    => 'required|confirmed|min:6'
        'pda'                         => 'required|unique:forms',
        'password'                    => 'required|min:8|confirmed',
        'password_confirmation'       => 'required|min:8',

    );

$data = Input::all();

$validation = Validator::make ($data, $rules);

        if ($validation->passes())
        {

                         //true

                } else

                      {
                           //false
                      }

how to set image path in laravel

 Normally :-

<img src="rootlaravel/asset/css/images/top.png">

in laravel :-

<img src="{{ asset('asset/css/images/top.png'); }}">

set path in laravel


{{ URL::to( 'admin/logout') }}


<a href="{{ URL::to( 'admin/logout') }}">Logout</a>

how to call css and js in laravel

 Path start from root directory :-

//like (laravel/admin_asset/css/style.css)

{{ HTML::style('admin_asset/css/style.css'); }}

{{ HTML::script('admin_asset/js/jquery.js'); }}

how to define dynamic title in laravel

First set section name (title) and value (Home page) in view pages  :-

@section('title')
Home page(define head title here)
@stop


And In  layout page call the title section :-
 <title>@yield('title')</title>

Remember which tab was active after refresh.

<link rel="stylesheet" href="http://code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
<script>

$(function() {
 
    var index = 'key';
  
    var dataStore = window.sessionStorage;
 
    try {
     
        var oldIndex = dataStore.getItem(index);
    } catch(e) {
     
        var oldIndex = 0;
    }
    $('#tabs').tabs({
      
        active : oldIndex,
      
        activate : function( event, ui ){
         
            var newIndex = ui.newTab.parent().children().index(ui.newTab);
         
            dataStore.setItem( index, newIndex )
        }
    });
    });
</script>

 /*-------------------------------------------------------------------------------------------------------------------------*/

<div id="tabs">
<ul>
<li><a href="#tabs-1">Lalit1</a></li>
<li><a href="#tabs-2">Lalit2</a></li>
<li><a href="#tabs-3">Lalit13</a></li>
</ul>
<div id="tabs-1">
<p>Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).</p>


</div>
<div id="tabs-2">
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. .</p>
</div>
<div id="tabs-3">
<p>It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English.</p>
</div>
</div>






Monday 17 November 2014

how to get date difference in javascript

<script>

function calcDate() {
var today = new Date();
var past = new Date(2010,05,01);
    var diff = Math.floor(today.getTime() - past.getTime());
    var day = 1000 * 60 * 60 * 24;

    var days = Math.floor(diff/day);
    var months = Math.floor(days/31);
    var years = Math.floor(months/12);

    var message = past.toDateString();
    message += " was "
    message += days + " days "
    message += months + " months "
    message += years + " years ago \n"

  alert(message);
  return false;
    }
</script>

Thursday 13 November 2014

detect copy, paste and cut behavior with jQuery

 <script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
        <style type="text/css">
        span{
            color:green;
            font-weight:bold;
        }
        </style>

 <label>Text Box : </label>
            <input id="textA" type="text" size="50" value="Copy, paste or cut any text here" />



<script type="text/javascript">
        $(document).ready(function() {
            $("#textA").bind({
                copy : function(){
                $('#message').text('copy behaviour detected!');
                },
                paste : function(){
                return false;  /*you can't paste in textbox*/
                //$('#message').text('paste behaviour detected!');
                },
                cut : function(){
                $('#message').text('cut behaviour detected!');
                }
            });
        });
        </script>

Saturday 8 November 2014

Drag and drop div into another div and change order through ajax

First create two tables table_name(fields = 'id','name','sort_order') and second is table_name(fields = 'id','t_id','name','sort_order').
create db connection in db file:-

in db.php file :-

<?php
mysql_connect("localhost", "root", "") or die ("Error connecting to mysql");
mysql_select_db("db_name");
?>
/*------------------------------------------------------------------------------------------*/
in index.php file :-

<?php
include("db.php");
?>
<!doctype html>

<html lang="en">
<head>
    <title>jQuery UI Sortable - Connect lists</title>
    <link rel="stylesheet" href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css" />
    <script src="http://code.jquery.com/jquery-1.8.3.js"></script>
    <script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>

    <style>
    .connectedSortable{min-height:100px;min-width:400px;list-style-type: none; margin: 0; padding: 0 0 2.5em; float: left; margin-right: 10px; }
   
    .connectedSortable li { margin: 0 5px 5px 5px; padding: 5px; font-size: 1.2em; width: 390px; }
    .sec h3 {
    background: none repeat scroll 0 0 #40E0D0;
    font-size: 22px;
    height: 47px;
    margin-left: 10px;
    padding: 0 7px;
    width: 372px;
    text-align:center
}
.sec {
    background-color: #9ACD32;
    float: left;
    margin-left: 10px;
    width: 413px;
}
.trans {
    -ms-transform: rotate(5deg);
    -webkit-transform: rotate(5deg);
    transform: rotate(5deg);
}
    </style>
    <script>
    $(function() {
        $( ".connectedSortable" ).sortable({
 cursor: "move",
            connectWith: ".connectedSortable",
            receive: function(event,ui){
                 console.log("old ui id = "+ui.sender.attr("id")+" new ul id = "+this.id+" li id "+$(ui.item).attr("id"));  
                                
                 if(ui.sender.attr("id") != this.id)
                 {

                  $(ui.item).removeClass("trans");
                  $.ajax({
                    type: "POST",
                    url: "logic.php",
                  data: { start: ui.sender.attr("id"), drop: this.id , id:$(ui.item).attr("id") }
                })/*.done(function( msg ) {
                              alert( "Data Saved: " + msg );
                            })*/;
                
                 }
                 
               
             } ,
           
    start: function( event, ui ) {
   
    ui.helper.addClass("trans");
   
   
   
    },
    stop: function( event, ui ) {
   
    $(this).find('li,div').removeClass("trans");
   
   
   
    }
    }).disableSelection();
       
        $('.connectedSortable , .team_sec ').sortable({
   
    update: function (event, ui) {
        var data = $(this).sortable('serialize');
  
   $.ajax({
                    type: "POST",
                    url: "order_change.php",
                  data: {id:$(ui.item).attr("id") , prev:ui.item.prev().attr('id'),team:this.id,data: $(this).sortable('serialize') }
                })/*.done(function( msg ) {
                              alert( "Data Saved: " + msg );
                            });*/
    }
});




       
    });
   
   
    </script>
</head>
<body>
<div class="team_sec">
<?php
$team_res = mysql_query("select * from team order by sort_order");
while($team = mysql_fetch_assoc($team_res))
{
?>

<div class="sec" id="sec_<?php echo $team['id'];?>">
<h3><?php echo $team['name'];?></h3>

<ul id="<?php echo $team['id'];?>" class="connectedSortable">

<?php
$ids = $team['id'];
$task_res = mysql_query("select * from task where t_id = $ids order by sort_order");
while($task = mysql_fetch_assoc($task_res))
{
?>
    <li id="<?php echo $task['id'];?>_<?php echo $team['id'];?>" value="<?php echo $team['id'];?>" class="ui-state-default"><?php echo $task['id'];?>__<?php echo $task['name'];?></li>
 <?php
 }
 ?>
</ul></div>
<?php } ?>
</div>
</body>
</html>

/*------------------------------------------------------------------------------------------*/

creat a php file for ajax request like logic.php :-

<?php
include("db.php");

$arid = explode('_',$_POST['id']);
$id = $arid[0];
$tid = $_POST['drop'];
$task_res = mysql_query("update task set t_id = '$tid' where id = $id");

?>
/*------------------------------------------------------------------------------------------*/
creat another php file for second ajax request like order_change.php :-

<?php
include("db.php");

$secid = explode('_',$_POST['id']);
$arr = explode('&',$_POST['data']);
if($secid[0]=="sec")
{

$count = 1;
foreach($arr as $ordr)
{

$ordid = explode('=',$ordr);
 $o_id = $ordid[1];
$task_res = mysql_query("update team set sort_order = '$count' where id = $o_id");
$count++;
}

}else
 {

 $arid = $_POST['team'];

$count = 1;
foreach($arr as $ordr)
{

$ordid = explode('[',$ordr);
 $o_id = $ordid[0];
$task_res = mysql_query("update task set sort_order = '$count' where t_id = $arid and id = $o_id");
$count++;
}
}
?>
/*-----------------------------------------end----------------------------------------------*/

Thursday 6 November 2014

manage multiple category tree in single table in php

 Create a table with catgory_id,name,parent,sort_order field

<?php
$g_link = mysql_connect( 'localhost', 'root', '');
        mysql_select_db('your_database_name');
       
       
$result = mysql_query("SELECT category_id,name,parent,sort_order FROM category ORDER BY parent,sort_order,name");
 
 
$category = array('categories' => array(),'parent_cats' => array());
 
        while ($row = mysql_fetch_assoc($result)) {
            
            $category['categories'][$row['category_id']] = $row;
            
            $category['parent_cats'][$row['parent']][] = $row['category_id'];
        }
        ?>


/*This function used for show add category (in select box for select parent category) in menu*/ 


<select name="cat">
<option value="0"></option>
<?php

function buildCategory($parent, $category,$name) {
            $html = "";
            if (isset($category['parent_cats'][$parent])) {
                
                foreach ($category['parent_cats'][$parent] as $cat_id) {
                    if (!isset($category['parent_cats'][$cat_id])) {
                        $html .= "<option value='".$category['categories'][$cat_id]['category_id']."'>" . trim($name."->". $category['categories'][$cat_id]['name'],"->") . "</option>";
                    }
                    if (isset($category['parent_cats'][$cat_id])) {
                        $html .= "<option value='".$category['categories'][$cat_id]['category_id']."'>" . trim($name."->".$category['categories'][$cat_id]['name'],"->") . "</option>";
                        $html .= buildCategory($cat_id, $category,trim($name."->".$category['categories'][$cat_id]['name'],"->"));
                        $html .= "</option>";
                    }
                }
                
            }
            return $html;
        }
        echo buildCategory(0, $category ,'');
?>
</select>
<?php
        echo '<br><br>';
        /*--------------------------------end-------------------------------------------------------------------------------------------------------------------------*/

/*This function used for show all categories in menu*/ 


function buildCategory1($parent, $category) {
            $html = "";
            if (isset($category['parent_cats'][$parent])) {
                $html .= "<ul>\n";
                foreach ($category['parent_cats'][$parent] as $cat_id) {
                    if (!isset($category['parent_cats'][$cat_id])) {
                        $html .= "<li>\n  <a href='#'>" .$category['categories'][$cat_id]['name'] . "</a>\n</li> \n";
                    }
                    if (isset($category['parent_cats'][$cat_id])) {
                        $html .= "<li>\n  <a href='#'>" .$category['categories'][$cat_id]['name'] . "</a> \n";
                        $html .= buildCategory1($cat_id, $category);
                        $html .= "</li> \n";
                    }
                }
                $html .= "</ul> \n";
            }
            return $html;
        }
        echo buildCategory1(0, $category);
/*--------------------------------end-------------------------------------------------------------------------------------------------------------------------*/

?>

Thursday 16 October 2014

how to make magento webpage available only for registered users

paste below code in header part :- 



<?php $myStatus = Mage::getSingleton('customer/session')->isLoggedIn() ?>
<?php if(!$myStatus): ?>

<style type="text/css">
.blankdiv{background-color:#000;
position:fixed;
z-index: 9001;
top:0px; height:100%;
left:0px;
width:100%; opacity: 0.65;
filter:alpha(opacity=65);}


#popupform1{height: 100%;
    left: 0;
    padding: 15px;
    position: fixed;
    top: 0;
    width:97%;
    z-index: 10001;
    }
   
#popupform1 .applyform{position:relative; overflow:auto;
background-color:#fff;
width:500px;
height:500px;  margin:5% auto auto auto;
z-index: 9002; padding:10px; border:10px solid #7F3814; }


#pclose{background-image: url("http://www.americanpowergear.com/close.png");
    background-position: left top;
    background-repeat: no-repeat;
    cursor: pointer;
    height: 25px;
    margin: 5% auto -6%;
    position: relative;
    right: -348px;
    text-indent: -9999px;
    top: 0;
    width: 25px;
    z-index: 9999;}
</style>







 
            
<div id="popupform1" style="display:block" width="500" height="500">
<div class="blankdiv" style="opacity:1!important; background-color: #FFFFFF;"></div>

<div class="applyform"><h1 align="center"> Welcome Login Form </h1>
<p id="contactArea">
<form id="login-form" method="post" action="baseurl/customer/account/loginPost/">       
<div class="content">
               
             <!-- <form id="login-form" method="post" action="http://www.americanpowergear.com/index.php/customer/account/loginPost/">-->
    <input type="hidden" name="form_key" value="<?php  echo Mage::getSingleton('core/session')->getFormKey(); ?>" />
    <div class="clearfix">
        <div class="registered-users">
            <div class="content">This is a demo store. Any orders placed through this store will not be honored or fulfilled.
            
                
                <div class="border"></div>
                <ul class="form-list">
                    <li>
                        <label class="required" for="email"><em>*</em>Email Address</label>
                        <div class="input-box">
                            <input type="text" title="Email Address" class="input-text required-entry validate-email" id="email" value="" name="login[username]">
                        </div>
                    </li>
                    <li>
                        <label class="required" for="pass"><em>*</em>Password</label>
                        <div class="input-box">
                            <input type="password" title="Password" id="pass" class="input-text required-entry validate-password" name="login[password]">
                        </div>
                    </li>
                                                        </ul>
               

               
                <div class="buttons-set">                   
                    <button id="send2" name="send" title="Login" class="button" type="submit"><span><span>Login</span></span></button>
                    
                </div>
            </div>
        </div>
        
                </div>
    </form>

<div id="backgroundPopup1" class="SkipMeIAmAlradyFixPushed" ></div>
</p>
</div>
</div>
<?php else: ?>

<?php endif ?>

Saturday 11 October 2014

how to check customer exist or not in magento

<?php
$websiteId = Mage::app()->getWebsite()->getId();
$email = 'abc@ptiwebtech.com';// Your Customers Email Here
   
function IscustomerEmailExists($email, $websiteId = null){
 $customer = Mage::getModel('customer/customer');

  if ($websiteId) {
            $customer->setWebsiteId($websiteId);
        }
        $customer->loadByEmail($email);
        if ($customer->getId()) {
            return $customer->getId();
        }
        return false;
    }
   
    $cust_exist = IscustomerEmailExists($email,$websiteId);

?>

get order sale customer by email in magento

<?php

$orders = Mage::getModel('sales/order')
->getCollection()
->addFieldToFilter('store_id', Mage::app()->getStore()->getId())
//->addAttributeToFilter('status', Mage_Sales_Model_Order::STATE_COMPLETE)
->addAttributeToFilter('customer_email', $email)// guest email id for filter
->addAttributeToSort('entity_id', 'DESC');

foreach($orders as $order) {
    $guest_email = $order->getCustomerEmail();
}

?>

how to get newsletter subcriber by email in magento

$subscriber = Mage::getModel('newsletter/subscriber')->loadByEmail($email);
$subcibe_mail = $subscriber->getSubscriberEmail();

simple mail function in php

<?php
$email = "abc@gmail.com"; 
$sub="Newsletter subcription";
   
$msg="<table border='1' cellspacing='5' cellpadding='5' align='center' width='600px'>
<tr><td colspan='5' align='center'>Thanks for Subcription</td></tr>

<tr>
<td align='center'>You coupn code for 10% discount</td>
<td>abc@123jk</td>
</tr>
</table>";

  $headers  = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .="From: yogi.lalit2391@gmail.com";
 
//mail($email,$sub,$msg,$headers);
?>

get current url in magento

$currentUrls = Mage::helper('core/url')->getCurrentUrl();

how to get cupon code by cupon code rule id in magento



<?php

$oRule = Mage::getModel('salesrule/rule')->load(1);//cupon code rule id.
echo $cuponcd = $oRule->getData('coupon_code');

?>

how to user subcribe dynamicaly in magento

$email = yoursubcriber@gmail.com;

Mage::getModel('newsletter/subscriber')->subscribe($email);

first time user get cupon code in magento


<?php
session_start();
$ses_id = session_id(); ?>
<?php $myStatus = Mage::getSingleton('customer/session')->isLoggedIn() ?>
<?php
if($_SESSION['browser_id']!=session_id() && $myStatus==false)
{
   
?>
<style type="text/css">

.blankdiv{background-color:#000;

position:fixed;

z-index: 9001;

top:0px; height:100%;

left:0px;

width:100%; opacity: 0.65;

filter:alpha(opacity=65);}





#popupform{height: 100%;

    left: 0;

    padding: 15px;

    position: fixed;

    top: 0;

    width:97%;

    z-index: 10001;

    }

   

#popupform .applyform{position:relative; overflow:auto;

background-color:#fff;

width:405px;

height:auto;  margin:5% auto auto auto;

z-index: 9002; padding:10px; border:10px solid #32499C; }





/*#pclose{background-image: url("<?php //echo $this->getSkinUrl('images/close.png'); ?>");

    background-position: left top;

    background-repeat: no-repeat;

    cursor: pointer;

    height: 25px;

    margin: 5% auto -6%;

    position: relative;

    right: -245px;

    text-indent: -9999px;

    top: 0;

    width: 25px;

    z-index: 9999;}*/
   
    .pop_h{color:#D36148;}
.button_pop{float: left;
    margin-left: 0px;
    min-width: 140px;
    background: none repeat scroll 0 0 #D36148;
    border: 0 none;
    border-radius: 10px;
    color: #FFFFFF;
    display: inline-block;
    font-size: 13px;
    font-weight: normal;
    line-height: 19px;
    padding: 7px 15px;
    text-align: center;
    text-transform: uppercase;
    vertical-align: middle;
    white-space: nowrap;}
    .button_pop_right{float: left;
    margin-left: 85px;
    min-width: 140px;
    background: none repeat scroll 0 0 #32499C;
    border: 0 none;
    border-radius: 10px;
    color: #FFFFFF;
    display: inline-block;
    font-size: 13px;
    font-weight: normal;
    line-height: 19px;
    padding: 7px 15px;
    text-align: center;
    text-transform: uppercase;
    vertical-align: middle;
    white-space: nowrap;}
    .news_btn {
    padding: 10px 0 13px;}
    .button_pop:hover {
    background: none repeat scroll 0 0 #32499C;
    cursor: pointer;
}
.button_pop_right:hover {
    background: none repeat scroll 0 0 #D36148;
    cursor: pointer;
}
</style>
<script type="text/javascript">

function apply()

{

document.getElementById("popupform").style.display="block";
   

}

window.onload = apply;

function vlid(){

if( document.subc.email.value == "" )
   {
   
   
    document.getElementById('err').style.display = "block";
     document.subc.email.focus();
   
     return false;
   }
}
 </script>
<div id="popupform" style="display:none">

  <div class="blankdiv"></div>

  <!--<div id="pclose" onclick="javascript:document.getElementById('popupform').style.display='none';">close</div>-->

    <div class="applyform">

        <p id="contactArea">

<div class="block-content">
            <div class="form-subscribe-header">
                <label for="newsletter"><h3 class="pop_h">First Time User only</h3></label>
                <p class="dic_msg">Get 10% discounts</p>
            </div>
            
             <div class="input-box">
            <p id="err" style="display:none;color:#FF0000;">Please insert your email address.</p>
            <form action="" method="post" name="subc">
           
               <input type="email"  title="Enter Email" name="email" spellcheck="false" autocorrect="off" autocapitalize="off" placeholder="Your email address...">

            </div>
            <div class="news_btn">
          <input class="button_pop" type="submit" name="sub" value="Submit" onclick="return vlid();">
           </form>
               <button class="button_pop_right" onclick="window.location=''">Skip</button>
               </div>
        </div>


 <div id="backgroundPopup" class="SkipMeIAmAlradyFixPushed"></div>

        </p>

    </div>

    </div>
    </div>



<?php
}
if($_POST['email']!="")
{
$email = $_POST['email'];
umask(0);
$websiteId = Mage::app()->getWebsite()->getId();
//$email = 'abc@ptiwebtech.com';// Your Customers Email Here
   
function IscustomerEmailExists($email, $websiteId = null){
 $customer = Mage::getModel('customer/customer');

  if ($websiteId) {
            $customer->setWebsiteId($websiteId);
        }
        $customer->loadByEmail($email);
        if ($customer->getId()) {
            return $customer->getId();
        }
        return false;
    }
   
    $cust_exist = IscustomerEmailExists($email,$websiteId);
   

$orders = Mage::getModel('sales/order')
->getCollection()
->addFieldToFilter('store_id', Mage::app()->getStore()->getId())
//->addAttributeToFilter('status', Mage_Sales_Model_Order::STATE_COMPLETE)
->addAttributeToFilter('customer_email', $email)
->addAttributeToSort('entity_id', 'DESC');

foreach($orders as $order) {
    $guest_email = $order->getCustomerEmail();
}

$subscriber = Mage::getModel('newsletter/subscriber')->loadByEmail($email);
$subcibe_mail = $subscriber->getSubscriberEmail();
?>

<?php    
    if($cust_exist==false && $guest_email=='' && $subcibe_mail=='')
   
{   
     Mage::getModel('newsletter/subscriber')->subscribe($email);
   
$oRule = Mage::getModel('salesrule/rule')->load(1);//cupon code rule  id
$cuponcd = $oRule->getData('coupon_code');
     $sub="Newsletter subcription";
   
$msg="<table border='1' cellspacing='5' cellpadding='5' align='center' width='600px'>
<tr><td colspan='5' align='center'>Thanks for Subcription</td></tr>

<tr>
<td align='center'>You coupn code for 10% discount</td>
<td>".$cuponcd."</td>
</tr>
</table>";

  $headers  = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .="From: mukesh@ptiwebtech.com";//.Mage::getStoreConfig('contacts/email/recipient_email');

mail($email,$sub,$msg,$headers);
$currentUrls = Mage::helper('core/url')->getCurrentUrl();

print("<script>window.location='$currentUrls'</script>");

}
   
    else { 
   
    echo '<div id="messages">You are already our Customer<span></div>';
   
    }
   
}   
   
$_SESSION['browser_id'] = session_id();

?>

Saturday 27 September 2014

how to set simple form captcha through js

<script>
function myFunction() {
    var x = Math.floor((Math.random() * 9) + 1);

    document.getElementById("cap1").innerHTML = x;
 var y = Math.floor((Math.random() * 9) + 1);
document.getElementById("cap2").innerHTML = y;
var z= x+y;
document.getElementById("hid_cap1").value = z;

}
function valcpa() {
var hidc = document.getElementById("hid_cap1").value;
var orgc = document.getElementById("org_cap1").value;
if(orgc=="")
{
document.getElementById("cap_msg").innerHTML = "*Please Enter captcha value.";
return false;
}
else if(hidc!=orgc)
{
document.getElementById("cap_msg").innerHTML = "*Please Enter sum of both value.";
return false;
}

else {
document.getElementById("cap_msg").innerHTML = "";
 }
}
</script>



<body onload="myFunction();">
<form action="" method="post">
 <table>
 <tr>
  <td><label><span id="cap1"></span>+<span id="cap2"></span> =</label></td>
  <td><input type="hidden" id="hid_cap1" name="hid_cap" value="" /><input type="text" name="org_cap" id="org_cap1" required="required" />
  <p id="cap_msg" style="color:#f00;"></p>
  </td>
  </tr>
 
  <tr>
  <td colspan="2">
 <input type="SUBMIT" name="" value="Submit"    CLASS="Submit-d-ship " onclick="return valcpa();">
  </td>
  </tr>
  </table>
  </form>
</body>

how to resize image in custom module in magento

 Open namespace/modulename/helper/data.php

paste following code in helper class :-

 <?php
class Namespace_Modulename_Helper_Data extends Mage_Core_Helper_Abstract
{

public function resizeImage($imageName, $width=NULL, $height=NULL, $imagePath=NULL)
{     
    $imagePath = str_replace("/", DS, $imagePath);
    $imagePathFull = Mage::getBaseDir('media') . DS . $imagePath . DS . $imageName;
    
    if($width == NULL && $height == NULL) {
        $width = 100;
        $height = 100;
    }
    $resizePath = $width . 'x' . $height;
    $resizePathFull = Mage::getBaseDir('media') . DS . $imagePath . DS . $resizePath . DS . $imageName;
            
    if (file_exists($imagePathFull) && !file_exists($resizePathFull)) {
        $imageObj = new Varien_Image($imagePathFull);
        $imageObj->constrainOnly(TRUE);
        $imageObj->keepAspectRatio(TRUE);   //set false if you don't want set image size in ratio (like:-100x100,200x200).
        $imageObj->resize($width,$height);
        $imageObj->save($resizePathFull);
    }
            
    $imagePath=str_replace(DS, "/", $imagePath);
    return Mage::getBaseUrl("media") . $imagePath . "/" . $resizePath . "/" . $imageName;
}
}

and  use in any template/phtml file of your module:-
 

<img src="<?php echo Mage::helper('modulename')->resizeImage('imagename.jpg', 100, 100, 'path/image'); ?>" style="padding:10px;">


Note :- it take automatically base url (www.domain.com/media/). So you put only your image url.

Thursday 25 September 2014

url rewrite to hide query sting in php

It rewrite url like :-

http://www.rootdirectory.com/index.php?sate=rajasthan&city=jaipur&land=malviyanagar

to :-

http://www.rootdirectory.com/rajasthan/jaipur/malviyanagar

create a .htaccess file on root directory and paste following code

RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^([a-zA-Z0-9]+|)/?$ index.php?state=$1 [QSA]

RewriteRule ^([a-zA-Z0-9]+|)/([a-zA-Z0-9]+|)/?$ index.php?state=$1&city=$2 [QSA]

RewriteRule ^([a-zA-Z0-9]+|)/([a-zA-Z0-9]+|)/([a-zA-Z0-9]+|)/?$ index.php?state=$1&city=$2&land=$3 [QSA]

After used it code you can access your query string value like :-

And last  on http://www.rootdirectory.com/index.php

paste following code :-

<div>

<a href="http://www.rootdirectory.com">home</a>
<a href="http://www.rootdirectory.com/rajasthan">Rajasthan</a>
<a href="http://www.rootdirectory.com/delhi/newdelhi">New Delhi</a>
<a href="http://www.rootdirectory.com/rajasthan/jaipur/malviyanagar">Malviya Nagar</a>
</div>


<?php

echo "<h2>".$_GET['state']."</h2>";
echo "<h2>".$_GET['city']."</h2>";

echo "<h2>".$_GET['land']."</h2>";

?>

Monday 22 September 2014

Add get directions maps to website

<!DOCTYPE html>
<html>
  <head>
    <title> Lalit Get Directions service</title>
    <style>
      html, body, #map-canvas {
        height: 600px;
        width: 600px;
       margin-left:150px;
       top:60px;
        padding: 0px
      }
      #panel {
        position: absolute;
        top: 5px;
        left: 50%;
        margin-left: -180px;
        z-index: 5;
        background-color: #fff;
        padding: 5px;
        border: 1px solid #999;
      }
    </style>
    <script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
    <script>
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;

function initialize() {
  directionsDisplay = new google.maps.DirectionsRenderer();
  var chicago = new google.maps.LatLng(41.850033, -87.6500523);
  var mapOptions = {
    zoom:7,
    center: chicago
  };
  map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
  directionsDisplay.setMap(map);
}

function calcRoute() {
  var start = document.getElementById('start').value;
  var end = document.getElementById('end').value;
  var request = {
      origin:start,
      destination:end,
      travelMode: google.maps.TravelMode.DRIVING
  };
  directionsService.route(request, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      directionsDisplay.setDirections(response);
    }
  });
}

google.maps.event.addDomListener(window, 'load', initialize);

    </script>
  </head>
  <body>
    <div id="panel">
    <b>Start: </b>
    <input type="text" value="jaipur,rajsthan" id="start">
    <b>End: </b>
    <input type="text" id="end">
    <input type="button" onClick="calcRoute();" value="Get Direction">
  
    </div>
    <div id="map-canvas"></div>
  </body>
</html>

how to add google address search map on website

<!DOCTYPE html>
<html>
  <head>
    <title> address search</title>
    <style>
      html, body, #map-canvas {
         height: 600px;
        width: 600px;
        padding: 0px;
        margin-left:100px;
        top:60px;
      }
      #panel {
        position: absolute;
        top: 5px;
        left: 50%;
        margin-left: -180px;
        z-index: 5;
        background-color: #fff;
        padding: 5px;
        border: 1px solid #999;
      }
    </style>
    <script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
    <script>
var geocoder;
var map;
function initialize() {
  geocoder = new google.maps.Geocoder();
  var latlng = new google.maps.LatLng(-34.397, 150.644);
  var mapOptions = {
    zoom: 10,
    center: latlng
  }
  map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}

function codeAddress() {
  var address = document.getElementById('address').value;
  geocoder.geocode( { 'address': address}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      map.setCenter(results[0].geometry.location);
      var marker = new google.maps.Marker({
          map: map,
          position: results[0].geometry.location
      });
    } else {
      alert('Geocode was not successful for the following reason: ' + status);
    }
  });
}

google.maps.event.addDomListener(window, 'load', initialize);

    </script>
  </head>
  <body>
    <div id="panel">
      <input id="address" type="textbox" value="Sydney, NSW">
      <input type="button" value="Geocode" onclick="codeAddress()">
    </div>
    <div id="map-canvas"></div>
  </body>
</html>

Thursday 18 September 2014

how to get category thumbnail image in magento

<?php  $catId = $_category->getId(); ?>
<?php $thumb = Mage::getModel('catalog/category')->load($catId)->getThumbnail();?>
<img src="<?php echo Mage::getBaseUrl('media').'catalog/category/'.$thumb;?>" >

Wednesday 17 September 2014

get all sale products from category and show on header top in magento

Note :-It's work only magneto 1.9 version because we used magento default funcnality.



On list page  will be show only simple products and and sale product show on tab.
 and set design according to your theme.

First open list.phtml file and replace all code with following  :-

<?php
    $_productCollection=$this->getLoadedProductCollection();
    $_helper = $this->helper('catalog/output');
?>
<?php if(!$_productCollection->count()): ?>
<p class="note-msg"><?php echo $this->__('There are no products matching the selection.') ?></p>
<?php else:

?>


<div class="header-minicart minicart1">
<a class="skip-link skip-cart " href="#header-cart12">
<span class="icon"></span>
<span class="label">closeout</span>
</a>

<div id="header-cart12" class="block block-cart skip-content">
<div id="minicart-error-message" class="minicart-message"></div>
<div id="minicart-success-message" class="minicart-message"></div>
<div class="minicart-wrapper">
<?php $i="";
$k = 0; ?>
<div>
<ul id="cart-sidebar" class="mini-products-list">
<?php foreach ($_productCollection as $_products): ?>
<?php  $specialprice = $_products->getSpecialPrice();
$specialPriceToDate = $_products->getSpecialToDate();

$specialdate = 1;
$today = 0;
if($specialPriceToDate!="")
{
$today = strtotime(date("Y-m-d"));
$specialdate = strtotime($specialPriceToDate);
}
if($specialprice!="" && $specialdate >= $today) {

$i = 0; ?>
<li class="item last odd" xmlns="http://www.w3.org/1999/html">
<a class="product-image" href="<?php echo $_products->getProductUrl() ?>" title="<?php echo $this->stripTags($this->getImageLabel($_products, 'small_image'), null, true) ?>">
<img height="50" width="50" alt="<?php echo $this->stripTags($this->getImageLabel($_products, 'small_image'), null, true) ?>" src="<?php echo $this->helper('catalog/image')->init($_products, 'small_image')->keepFrame(false)->resize(50); ?>">
</a>
<div class="product-details">
<?php $_productsNameStripped = $this->stripTags($_products->getName(), null, true); ?>
<p class="product-name">
<a href="<?php echo $_products->getProductUrl() ?>" title="<?php echo $_productsNameStripped; ?>"><?php echo $_helper->productAttribute($_products, $_products->getName() , 'name'); ?></a>
</p>
<table class="info-wrapper">
<tbody>
<tr>
<th>Price</th>
<td>
<span class="price"><?php echo $this->getPriceHtml($_products, true) ?></span>
</td>
</tr>

</tbody>
</table>
</div>
</li>
<?php $i++;
$k++;
}

?>
<?php endforeach; ?>

</ul>
<?php if($i==0){
?>
<p class="block-subtitle">No Sale item in this category!</p>
<?php
}
?>

</div>
</div>
</div>

</div>


<div class="category-products">
    <?php echo $this->getToolbarHtml() ?>
    <?php // List mode ?>
    <?php if($this->getMode()!='grid'): ?>
    <?php $_iterator = 0; ?>
    <ol class="products-list" id="products-list">
    <?php foreach ($_productCollection as $_product): ?>
<?php  $specialprices = $_product->getSpecialPrice();
$specialPriceToDate = $_product->getSpecialToDate();
$specialdate = 0;
$today = 1;
if($specialPriceToDate!="")
{
$specialprices="";
$today = strtotime(date("Y-m-d"));
$specialdate = strtotime($specialPriceToDate);
}
if($specialprices=="" && $specialdate < $today) { ?>

        <li class="item<?php if( ++$_iterator == sizeof($_productCollection) ): ?> last<?php endif; ?>">
            <?php // Product Image ?>
            <a href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $this->stripTags($this->getImageLabel($_product, 'small_image'), null, true) ?>" class="product-image">
                <?php /* Based on the native RWD styling, product images are displayed at a max of ~400px wide when viewed on a
                        one column page layout with four product columns from a 1280px viewport. For bandwidth reasons,
                        we are going to serve a 300px image, as it will look fine at 400px and most of the times, the image
                        will be displayed at a smaller size (eg, if two column are being used or viewport is smaller than 1280px).
                        This $_imgSize value could even be decreased further, based on the page layout
                        (one column, two column, three column) and number of product columns. */ ?>
                <?php $_imgSize = 300; ?>
                <img id="product-collection-image-<?php echo $_product->getId(); ?>"
                     src="<?php echo $this->helper('catalog/image')->init($_product, 'small_image')->keepFrame(false)->resize($_imgSize); ?>"
                     alt="<?php echo $this->stripTags($this->getImageLabel($_product, 'small_image'), null, true) ?>" />
            </a>
            <?php // Product description ?>
            <div class="product-shop">
                <div class="f-fix">
                    <div class="product-primary">
                        <?php $_productNameStripped = $this->stripTags($_product->getName(), null, true); ?>
                        <h2 class="product-name"><a href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $_productNameStripped; ?>"><?php echo $_helper->productAttribute($_product, $_product->getName() , 'name'); ?></a></h2>
                        <?php if($_product->getRatingSummary()): ?>
                        <?php echo $this->getReviewsSummaryHtml($_product) ?>
                        <?php endif; ?>

                        <?php
                            $_nameAfterChildren = $this->getChild('name.after')->getSortedChildren();
                            foreach($_nameAfterChildren as $_nameAfterChildName):
                                $_nameAfterChild = $this->getChild('name.after')->getChild($_nameAfterChildName);
                                $_nameAfterChild->setProduct($_product);
                        ?>
                            <?php echo $_nameAfterChild->toHtml(); ?>
                        <?php endforeach; ?>
                    </div>
                    <div class="product-secondary">
                        <?php echo $this->getPriceHtml($_product, true) ?>
                    </div>
                    <div class="product-secondary">
                        <?php if($_product->isSaleable() && !$_product->canConfigure()): ?>
                            <p class="action"><button type="button" title="<?php echo $this->__('Add to Cart') ?>" class="button btn-cart" onclick="setLocation('<?php echo $this->getAddToCartUrl($_product) ?>')"><span><span><?php echo $this->__('Add to Cart') ?></span></span></button></p>
                        <?php elseif($_product->isSaleable()): ?>
                            <p class="action"><a title="<?php echo $this->__('View Details') ?>" class="button" href="<?php echo $_product->getProductUrl() ?>"><?php echo $this->__('View Details') ?></a></p>
                        <?php else: ?>
                            <p class="action availability out-of-stock"><span><?php echo $this->__('Out of stock') ?></span></p>
                        <?php endif; ?>
                        <ul class="add-to-links">
                            <?php if ($this->helper('wishlist')->isAllow()) : ?>
                                <li><a href="<?php echo $this->helper('wishlist')->getAddUrl($_product) ?>" class="link-wishlist"><?php echo $this->__('Add to Wishlist') ?></a></li>
                            <?php endif; ?>
                            <?php if($_compareUrl=$this->getAddToCompareUrl($_product)): ?>
                                <li><span class="separator">|</span> <a href="<?php echo $_compareUrl ?>" class="link-compare"><?php echo $this->__('Add to Compare') ?></a></li>
                            <?php endif; ?>
                        </ul>
                    </div>
                    <div class="desc std">
                        <?php echo $_helper->productAttribute($_product, $_product->getShortDescription(), 'short_description') ?>
                        <a href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $_productNameStripped ?>" class="link-learn"><?php echo $this->__('Learn More') ?></a>
                    </div>
                </div>
            </div>
        </li>
<?php } ?>
    <?php endforeach; ?>
    </ol>
    <script type="text/javascript">decorateList('products-list', 'none-recursive')</script>

    <?php else: ?>

    <?php // Grid Mode ?>

    <?php $_collectionSize = $_productCollection->count() ?>
    <?php $_columnCount = $this->getColumnCount(); ?>
    <ul class="products-grid products-grid--max-<?php echo $_columnCount; ?>-col">
        <?php $i=0; foreach ($_productCollection as $_product): ?>
            <?php /*if ($i++%$_columnCount==0): ?>
            <?php endif*/ ?>
<?php  $specialprices = $_product->getSpecialPrice();
$specialPriceToDate = $_product->getSpecialToDate();
$specialdate = 0;
$today = 1;
if($specialPriceToDate!="")
{
$specialprices="";
$today = strtotime(date("Y-m-d"));
$specialdate = strtotime($specialPriceToDate);
}
if($specialprices=="" && $specialdate < $today) { ?>            <li class="item<?php if(($i-1)%$_columnCount==0): ?> first<?php elseif($i%$_columnCount==0): ?> last<?php endif; ?>">
                <a href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $this->stripTags($this->getImageLabel($_product, 'small_image'), null, true) ?>" class="product-image">
                    <?php $_imgSize = 210; ?>
                    <img id="product-collection-image-<?php echo $_product->getId(); ?>"
                         src="<?php echo $this->helper('catalog/image')->init($_product, 'small_image')->resize($_imgSize); ?>"
                         alt="<?php echo $this->stripTags($this->getImageLabel($_product, 'small_image'), null, true) ?>" />
                </a>
                <div class="product-info">
                    <h2 class="product-name"><a href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $this->stripTags($_product->getName(), null, true) ?>"><?php echo $_helper->productAttribute($_product, $_product->getName(), 'name') ?></a></h2>

                    <?php
                        $_nameAfterChildren = $this->getChild('name.after')->getSortedChildren();
                        foreach($_nameAfterChildren as $_nameAfterChildName):
                            $_nameAfterChild = $this->getChild('name.after')->getChild($_nameAfterChildName);
                            $_nameAfterChild->setProduct($_product);
                    ?>
                        <?php echo $_nameAfterChild->toHtml(); ?>
                    <?php endforeach; ?>

                    <?php echo $this->getPriceHtml($_product, true) ?>
                    <?php if($_product->getRatingSummary()): ?>
                    <?php echo $this->getReviewsSummaryHtml($_product, 'short') ?>
                    <?php endif; ?>
                    <div class="actions">
                        <?php if($_product->isSaleable() && !$_product->canConfigure()): ?>
                            <button type="button" title="<?php echo $this->__('Add to Cart') ?>" class="button btn-cart" onclick="setLocation('<?php echo $this->getAddToCartUrl($_product) ?>')"><span><span><?php echo $this->__('Add to Cart') ?></span></span></button>
                        <?php elseif($_product->isSaleable()): ?>
                            <a title="<?php echo $this->__('View Details') ?>" class="button" href="<?php echo $_product->getProductUrl() ?>"><?php echo $this->__('View Details') ?></a>
                        <?php else: ?>
                            <p class="availability out-of-stock"><span><?php echo $this->__('Out of stock') ?></span></p>
                        <?php endif; ?>
                        <ul class="add-to-links">
                            <?php if ($this->helper('wishlist')->isAllow()) : ?>
                                <li><a href="<?php echo $this->helper('wishlist')->getAddUrl($_product) ?>" class="link-wishlist"><?php echo $this->__('Add to Wishlist') ?></a></li>
                            <?php endif; ?>
                            <?php if($_compareUrl=$this->getAddToCompareUrl($_product)): ?>
                                <li><span class="separator">|</span> <a href="<?php echo $_compareUrl ?>" class="link-compare"><?php echo $this->__('Add to Compare') ?></a></li>
                            <?php endif; ?>
                        </ul>
                    </div>
                </div>
            </li>
<?php } ?>
            <?php /*if ($i%$_columnCount==0 || $i==$_collectionSize): ?>
            <?php endif*/ ?>
        <?php endforeach ?>
    </ul>
    <script type="text/javascript">decorateGeneric($$('ul.products-grid'), ['odd','even','first','last'])</script>
    <?php endif; ?>

    <div class="toolbar-bottom">
        <?php echo $this->getToolbarHtml() ?>
    </div>
</div>
<?php endif; ?>

<?php
    //set product collection on after blocks
    $_afterChildren = $this->getChild('after')->getSortedChildren();
    foreach($_afterChildren as $_afterChildName):
        $_afterChild = $this->getChild('after')->getChild($_afterChildName);
        $_afterChild->setProductCollection($_productCollection);
    ?>
    <?php echo $_afterChild->toHtml(); ?>
<?php endforeach; ?>


Tuesday 16 September 2014

how to remove .php from urls with htaccess in php

url :-
http://hostname/product.php

create a .htaccess file on root directory  and paste following code :-

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php

then you can access set your link like :-
 http://hostname/product

Tuesday 9 September 2014

magento product share on pintrest

 Set following code on product view page:-

<script type="text/javascript">
(function(d){
    var f = d.getElementsByTagName('SCRIPT')[0], p = d.createElement('SCRIPT');
    p.type = 'text/javascript';
    p.async = true;
    p.src = 'http://assets.pinterest.com/js/pinit.js';
    f.parentNode.insertBefore(p, f);
}(document));
</script>

 <a href="http://www.pinterest.com/pin/create/button?url=<?php echo $this->helper('catalog/product')->getProductUrl($_product); ?>&media=<?php echo $this->helper('catalog/image')->init($_product, 'small_image')->resize(600,400) ?>&description=<?php echo $_helper->productAttribute($_product, nl2br($_product->getShortDescription()), 'short_description') ?>" data-pin-do="buttonPin" data-pin-config="above">
        <img src="http://assets.pinterest.com/images/pidgets/pin_it_button.png" />
    </a>