Thursday, September 17, 2015

Magento - how to list most viewed product

$storeId = Mage::app()->getStore()->getId();     
// Get most viewed product collection
$products = Mage::getResourceModel('reports/product_collection')
    ->addAttributeToSelect('*')    
    ->setStoreId($storeId)
    ->addStoreFilter($storeId)
    ->addAttributeToSelect(array('name', 'price', 'minimal_price', 'small_image'))
    ->addViewsCount()
    ->setPageSize(6);

Mage::getSingleton('catalog/product_status')
        ->addVisibleFilterToCollection($products);
Mage::getSingleton('catalog/product_visibility')
        ->addVisibleInCatalogFilterToCollection($products);
       
$mostvieweddata= $products->getData();     // most view product   

Tuesday, September 15, 2015

Magento-How to Get Related Products by product Id

<?php
$model = Mage::getModel('catalog/product');
$product = $model->load($product_id);

// Get all related product ids of $product.
$allRelatedProductIds = $product->getRelatedProductIds();

foreach ($allRelatedProductIds as $id) {
            $relatedProduct = $model->load($id);

            // get Product's name
            echo $relatedProduct->getName();

            // get product's short description
            echo $relatedProduct->getShortDescription();

            // get Product's Long Description
            echo $relatedProduct->getDescription();

            // get Product's Regular Price
            echo $relatedProduct->getPrice();

            // get Product's Special price
            echo $relatedProduct->getSpecialPrice();

            // get Product's Url
            echo $relatedProduct->getProductUrl();

            // get Product's image Url
            echo $relatedProduct->getImageUrl();

        }
?>

Monday, August 10, 2015

Wordpress- get facebook like count by url

Wordpress-  get facebook like count by url

$link   = get_permalink( $post->ID );
// make the call
$call   = 'https://graph.facebook.com/fql?q=SELECT%20like_count%20FROM%20link_stat%20WHERE%20url=%27' . urlencode( $link ) . '%27';
// do the call
$rmget  = wp_remote_get( $call, array( 'sslverify' => false ) );
// error. bail.
if( is_wp_error( $rmget ) ) {
    return false;
}
// parse return values
$return = json_decode( $rmget['body'] );
// bail with no decoded
if ( empty( $return ) || empty( $return->data ) || empty( $return->data[0] ) || empty( $return->data[0]->like_count ) ) {
    return false;
}

// get the count
echo 'CONT is ', $count  = $return->data[0]->like_count;

Monday, July 13, 2015

Magento - set cron using cpanel

  1. Go to cpanel login
  2. Look for Cron section
  3. If you know the path of the cron file in the filemanager, enter the command like below. You can set cron for minutes, hourly, daily, monthly or for weekdays.
  4.  
  5.  If you don’t know the file path then use this command and configuration. As said you can schedule the cron as you want, I have configured here to run the cron every 5 minutes. 

Sunday, July 12, 2015

Magento - set cron using cpanel

Magento - set cron using cpanel

wget http://www.your-site.com/cron.php >/dev/null 2>&1

In cron.php add after line 47
$isShellDisabled = true;

Wednesday, July 8, 2015

jQuery- All child checkbox checked on checked in jquery


<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script>
var nocon = jQuery.noConflict();
nocon(document).ready(function(){

  nocon(".chk").click(function(ev) {

    nocon(this).siblings('ul').find("input[type='checkbox']").prop('checked', this.checked);
        ev.stopImmediatePropagation();
  });
});
</script>

<ul><li><input type="checkbox" class="chk"><a href="">1</a>
   <ul>
   <li>
   <input type="checkbox"class="chk"><a href="">2_1</a>
                       <ul>
                       <li><input type="checkbox" class="chk"><a href="">3_1</a></li>
                       <li><input type="checkbox" class="chk"><a href="">3_2</a></li>
                       </ul>
                   
                      </li>
                    <li>
                      <input type="checkbox"class="chk"><a href="">2_2</a>
                       <ul>
                       <li><input type="checkbox" class="chk"><a href="">3_3</a></li>
                       <li><input type="checkbox" class="chk"><a href="">3_4</a></li>
                       </ul>
                   
                      </li>
                      </ul>
                      </li>
        <li><input type="checkbox" class="chk"><a href="">1</a>
   <ul>
   <li>
   <input type="checkbox"class="chk"><a href="">2_1</a>
                       <ul>
                       <li><input type="checkbox" class="chk"><a href="">3_1</a></li>
                       <li><input type="checkbox" class="chk"><a href="">3_2</a></li>
                       </ul>
                   
                      </li>
                    <li>
                      <input type="checkbox"class="chk"><a href="">2_2</a>
                       <ul>
                       <li><input type="checkbox" class="chk"><a href="">3_3</a></li>
                       <li><input type="checkbox" class="chk"><a href="">3_4</a></li>
                       </ul>
                   
                      </li>
                      </ul>
                      </li>           
                   
                      </ul>

Wednesday, July 1, 2015

Magento- Images re-size in Magento


Best article Click here

Magento- Resize Product image without white space in magento

Magento-  Resize Product image without white space in magento

<?php echo $this->helper('catalog/image')->init($_product, 'small_image')->keepFrame(false)->resize(210,210); ?>

Thursday, June 4, 2015

javascript- dynamically adding file upload fields to a form using javascript

<script language="javascript" type="text/javascript">
       var a=1;
        function AddMoreImages() {

         
            var fileUploadarea = document.getElementById("fileUploadarea");
          
            //var newLine = document.createElement("br");
            //fileUploadarea.appendChild(newLine);
            var newFile = document.createElement("input");
            newFile.type = "file";
          

      
             
            newFile.setAttribute("id", "FileUpload" + a);
            newFile.setAttribute("name", "file[]");
            newFile.setAttribute("class", "browse-snap");
            var div = document.createElement("div");
            div.appendChild(newFile);
            div.setAttribute("id", "div" + a );
            fileUploadarea.appendChild(div);
          
             var newbot= document.createElement("input");
                newbot.type="Button";
                newbot.setAttribute("id","b" + a);
                newbot.setAttribute("value","remove" + a);
                newbot.setAttribute("class","close-btn");
                newbot.setAttribute("onclick","deletefile(this.id);");
                var divid=document.getElementById("div" + a);
               fileUploadarea.appendChild(div).appendChild(newbot);
             
            a++;
            return false;
        }
      
        function deletefile(abf)
        {
        a--;
        var abf1 = abf.split("b");
        //var uplod=document.getElementById("fileUploadarea");
        var im=document.getElementById("div" + abf1[1]);
        im.parentNode.removeChild(im);
        return false;
      
        }
    </script>
<body>
    <form id="form1">
    <div>
        <div id="fileUploadarea">
          
        </div>
        &nbsp;
        <input style="display: block;" id="btnAddMoreImages" type="button" value="Add more images" onClick="AddMoreImages();" />
      
    </div>
    </form>
</body>
</html>

PHP- download file in php

PHP- download file in php

function Download($path, $speed = null)
{
if (is_file($path) === true)
    {
set_time_limit(0);
while (ob_get_level() > 0)
        {
            ob_end_clean();
        }
$size = sprintf('%u', filesize($path));
        $speed = (is_null($speed) === true) ? $size : intval($speed) * 1024;
        header('Expires: 0');
        header('Pragma: public');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Content-Type: application/octet-stream');
        header('Content-Length: ' . $size);
        header('Content-Disposition: attachment; filename="' . basename($path) . '"');
        header('Content-Transfer-Encoding: binary');

        for ($i = 0; $i <= $size; $i = $i + $speed)
        {
            echo file_get_contents($path, false, null, $i, $speed);

            while (ob_get_level() > 0)
            {
                ob_end_clean();
            }

            flush();
            sleep(1);
        }

        exit();
    }

    return false;
}
echo Download($file_path='$file_path='C:\wamp\www\s.pdf'',500);

Magento - how to get product all image in magento

Magento - how to get product all image in magento

<?php
$product = Mage::getModel('catalog/product')->load($_product->getId());
             foreach ($product->getMediaGalleryImages() as $image) {
                        echo var_export($image->getUrl());
                       
   } ?>

Magento-how to get category thumbnail image in magento

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

Magento- get current url in magento

Magento- get current url in magento 
$currentUrls = Mage::helper('core/url')->getCurrentUrl();

Friday, May 29, 2015

Magento - Change options of configurable product to radio button

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


</script>

Monday, May 18, 2015

Wordpress- Some very useful plugins

Wordpress- Some very useful plugins 

1. Plugin for managing custom post types, custom taxonomies and custom fields.
 Types :  https://wordpress.org/plugins/types/

2.Append any number of items from your WordPress Media Library to Posts, Pages, and Custom Post Types.
Attachments : https://wordpress.org/plugins/attachments/

3. Add Multiple Featured Images To WordPress Posts
Dynamic Featured Image : https://wordpress.org/plugins/dynamic-featured-image/screenshots/ 

4. WordPress user management plugin. Custom user profile, custom Login, registration with extra fields and many more.
User Meta : https://wordpress.org/plugins/user-meta/

5.  Responsive Menu : https://wordpress.org/plugins/responsive-menu/
6. Contact Form 7  : https://wordpress.org/plugins/contact-form-7/

7.  Better Notifications for WordPress : Send customisable HTML emails to your users for different WordPress notifications.
https://wordpress.org/plugins/bnfw/

8. : Front End PM:  Front End PM is a Private Messaging system and a secure contact form to your WordPress site.This is full functioning messaging system from front end.

9. Custom Favicon:  https://wordpress.org/plugins/custom-favicon/

10. https://wordpress.org/plugins/custom-taxonomy-category-and-term-fields/screenshots/





Wednesday, May 13, 2015

Wordpress- get custom usermeta with Types plugin

 Wordpress- get custom  usermeta with Types plugin


echo do_shortcode('[types usermeta="user-badges-label"  proportional="true" user_id="'.$userid.'"]');

jQuery- to get Index using class

jQuery- to get Index using  class
 
 
jQuery(document).ready(function() { 
 jQuery( ".class-name" ).each(function( index ) {
 alert(index);
 
 });
}); 

Monday, May 11, 2015

Megento- Get product attribute drop-down by attibute id

 Megento- Get product attribute drop-down by attibute id

<select name="attribute_name">
                  <option value="">Color</option>
                   <?php
                      $attribute_id = 148;
                    $valuesCollection = Mage::getResourceModel('eav/entity_attribute_option_collection')
                    ->setAttributeFilter($attribute_id)
                    ->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();       
                    ?>
                    <option value="<?php echo $procategorydata['option_id'] ?>"><?php echo $procategorydata['value'] ?></option>
                    <?php
                    }
                    ?>                 
                </select>  

Magento- Create Product programmmatically

 Magento- Create Product programmmatically

<?php
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
$product = Mage::getModel('catalog/product');

try{
$product
//    ->setStoreId(1) //you can set data in store scope
    ->setWebsiteIds(array(1)) //website ID the product is assigned to, as an array
    ->setAttributeSetId(3) //ID of a attribute set named 'default'
    ->setTypeId('simple') //product type
    ->setCreatedAt(strtotime('now')) //product creation time
//    ->setUpdatedAt(strtotime('now')) //product update time

    ->setSku('testsku61') //SKU
    ->setName('test product21') //product name
    ->setWeight(4.0000)
    ->setStatus(1) //product status (1 - enabled, 2 - disabled)
    ->setTaxClassId(4) //tax class (0 - none, 1 - default, 2 - taxable, 4 - shipping)
    ->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH) //catalog and search visibility
    ->setManufacturer(28) //manufacturer id
    ->setColor(24)
    ->setNewsFromDate('06/26/2014') //product set as new from
    ->setNewsToDate('06/30/2014') //product set as new to
    ->setCountryOfManufacture('AF') //country of manufacture (2-letter country code)

    ->setPrice(11.22) //price in form 11.22
    ->setCost(22.33) //price in form 11.22
    ->setSpecialPrice(00.44) //special price in form 11.22
    ->setSpecialFromDate('06/1/2014') //special price from (MM-DD-YYYY)
    ->setSpecialToDate('06/30/2014') //special price to (MM-DD-YYYY)
    ->setMsrpEnabled(1) //enable MAP
    ->setMsrpDisplayActualPriceType(1) //display actual price (1 - on gesture, 2 - in cart, 3 - before order confirmation, 4 - use config)
    ->setMsrp(99.99) //Manufacturer's Suggested Retail Price

    ->setMetaTitle('test meta title 2')
    ->setMetaKeyword('test meta keyword 2')
    ->setMetaDescription('test meta description 2')

    ->setDescription('This is a long description')
    ->setShortDescription('This is a short description')

    ->setMediaGallery (array('images'=>array (), 'values'=>array ())) //media gallery initialization
    ->addImageToMediaGallery('media/catalog/product/1/0/10243-1.png', array('image','thumbnail','small_image'), false, false) //assigning image, thumb and small image to media gallery

    ->setStockData(array(
                       'use_config_manage_stock' => 0, //'Use config settings' checkbox
                       'manage_stock'=>1, //manage stock
                       'min_sale_qty'=>1, //Minimum Qty Allowed in Shopping Cart
                       'max_sale_qty'=>2, //Maximum Qty Allowed in Shopping Cart
                       'is_in_stock' => 1, //Stock Availability
                       'qty' => 999 //qty
                   )
    )

    ->setCategoryIds(array(3, 10)); //assign product to categories
$product->save();

}catch(Exception $e){
Mage::log($e->getMessage());
}

?>

Friday, May 8, 2015

Magento- Get product Collection

Magento-  Get product Collection

The following shows how to filter by a range of values (greater than AND less than)

$collection = Mage::getModel('catalog/product')->getCollection();
$collection->addAttributeToSelect('name');      
$collection->addAttributeToSelect('orig_price');        
//filter for products whose orig_price is greater than (gt) 100
$collection->addFieldToFilter(array(
        array('attribute'=>'orig_price','gt'=>'100'),
));     
//AND filter for products whose orig_price is greater than (lt) 130
$collection->addFieldToFilter(array(
        array('attribute'=>'orig_price','lt'=>'130'),
));

Magento : Create extension package

Magento : Create extension package Click Here

Magento - Get all options of a dropdown or multiselect attribute

Magento : Get all options of a dropdown or multiselect attribute

$arg_attribute = "manufacturer";//this may be any attribute code

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

echo "<pre />";

print_r($options);

Magento- Change page layout from controller


Magento - Change options of configurable product to radio button

To  Change options of configurable product to radio button

Replace the configurable.phtml code with below code:

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


</script>

Monday, March 30, 2015

Ajax request , response using jQuery

Ajax request , response using jQuery


<a onclick="callController();" href="javascript:void(0)">View More Articles</a>

<script type="text/javascript">
function callController(){
    
       new Ajax.Request("REQUEST FILE PATH HERE", {
           method: 'Post',
           parameters: {"pg_num":"<?php echo '1';?>"},
           onComplete: function(transport) {
            alert(transport.responseText);
           }
       });
   }
</script>

Thursday, March 26, 2015

jQuery:Tab Hide show

<ul class="tab-cat-name">
    <li>
        <a class="" href="javascript:void(0)" onclick="ShowHideTab('1')">Tab1</a>
        <a href="javascript:void(0)" onclick="ShowHideTab('2')" class="active">Tab2</a>
    </li>
</ul>
<div id="show_hide_1" class="tab-listing" style="display: none;">           
Content1
</div>
<div style="" id="show_hide_2" class="tab-listing">
Content2
</div>
       
<script type="text/javascript">
function ShowHideTab(current){
    jQuery( ".tab-listing" ).each(function( index ) {
        var toshow= index+1;
            if(current==toshow){
            jQuery('#show_hide_'+toshow).fadeIn(1000);
            }else{
            jQuery('#show_hide_'+toshow).fadeOut(1000);
            }
 });
}  
</script>

Wednesday, March 11, 2015

PHP-Load other page / landing page on first time url hit

Load other page / landing page on first time url hit



$ref_url = $_SERVER['HTTP_REFERER'];
$actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

if ($ref_url == '' && $actual_link  == 'http://your-site/') {  
    header('Location:http://your-site/landingpage.html');
    exit;
}


Njoy  :) :) 

Saturday, January 17, 2015

Add Class to fixed header

    <script>
    /*############fix menu##############*/
    jQuery("document").ready(function($){
    var nav = $('#menu');
    $(window).scroll(function () {
    if ($(this).scrollTop() > 136) {
    nav.addClass("f-nav");
    } else {
    nav.removeClass("f-nav");
    }
    });
   
    });
    </script>
<style>
.f-nav { .position :fixed;}
</style>

Friday, January 16, 2015

Magento -Magento how to get configurable product attributes option

<?php $cProduct = Mage::getModel('catalog/product')->load($_product->getId());
            //check if product is a configurable type or not
            if ($cProduct->getData('type_id') == "configurable")
            {
                //get the configurable data from the product
                $config = $cProduct->getTypeInstance(true);
                //loop through the attributes
                foreach($config->getConfigurableAttributesAsArray($cProduct) as $attributes)
                {
                    ?>
                    <dl>
                        <dt><label class="required"><em>*</em><?php echo $attributes["label"]; ?></label></dt>
                        <dd>
                            <div class="input-box">
                                <select name="super_attribute[<?php echo $attributes['attribute_id'] ?>]" id="attribute<?php echo $attributes['attribute_id'] ?>">
                                    <?php
                                    foreach($attributes["values"] as $values)
                                    {
                                        echo "<option>".$values["label"]."</option>";
                                    }
                                    ?>
                                </select>
                            </div>
                        </dd>
                    </dl>
                    <?php
                }
            }?>

Thursday, January 8, 2015

Magento - Custom layout in magneto like 1column

Follow the following steps :

Step 1.  add
app/etc/modules/Easylife_Layout.xml

<?xml version="1.0"?>
<config>
    <modules>
        <Easylife_Layout>
            <active>true</active>
            <codePool>local</codePool>
            <depends>
                <Mage_Page />
            </depends>
        </Easylife_Layout>
    </modules>
</config>

Step 2.  add
app/code/local/Easylife/Layout/etc/config.xml

<?xml version="1.0"?>
<config>
    <modules>
        <Easylife_Layout>
            <version>0.0.1</version>
        </Easylife_Layout>
    </modules>
    <global>
        <page>
            <layouts>
                <lookbook module="page" translate="label">
                    <label>Lookbook</label>
                    <template>page/1column-lookbook.phtml</template>
                    <layout_handle>lookbook</layout_handle>
                </lookbook>
            </layouts>
        </page>
    </global>
    <frontend>
        <layout>
            <updates>
                <easylife_layout>
                    <file>easylife_layout.xml</file>
                </easylife_layout>
            </updates>
        </layout>
    </frontend>
</config>
Step 3.  add
app/design/frontend/{interface}/{theme}/layout/easylife_layout.xml

<?xml version="1.0"?>
<layout>
    <lookbook translate="label">
        <label>Lookbook</label>
        <reference name="root">
            <action method="setTemplate"><template>page/1column-lookbook.phtml</template></action>
            <action method="setIsHandle"><applied>1</applied></action>
        </reference>
    </lookbook>
</layout>