Friday, May 29, 2015

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 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 25, 2015

CSS- Star Rating Input using CSS and HTML

CSS- Star Rating Input using CSS and HTML

<p>
      Rating:
      <span class="starRating">
        <input id="rating5" type="radio" name="rating" value="5">
        <label for="rating5">5</label>
        <input id="rating4" type="radio" name="rating" value="4">
        <label for="rating4">4</label>
        <input id="rating3" type="radio" name="rating" value="3" checked>
        <label for="rating3">3</label>
        <input id="rating2" type="radio" name="rating" value="2">
        <label for="rating2">2</label>
        <input id="rating1" type="radio" name="rating" value="1">
        <label for="rating1">1</label>
      </span>
    </p>
   
    <style>
    .starRating:not(old){
          display        : inline-block;
          width          : 7.5em;
          height         : 1.5em;
          overflow       : hidden;
          vertical-align : bottom;
        }

        .starRating:not(old) > input{
          margin-right : -100%;
          opacity      : 0;
        }

        .starRating:not(old) > label{
          display         : block;
          float           : right;
          position        : relative;
          background      : url('star-off.png');
          background-size : contain;
        }

        .starRating:not(old) > label:before{
          content         : '';
          display         : block;
          width           : 1.5em;
          height          : 1.5em;
          background      : url('star-on.png');
          background-size : contain;
          opacity         : 0;
          transition      : opacity 0.2s linear;
        }

        .starRating:not(old) > label:hover:before,
        .starRating:not(old) > label:hover ~ label:before,
        .starRating:not(:hover) > :checked ~ label:before{
          opacity : 1;
        }
    </style>

Note: Be sure  'star-off.png' and 'star-on.png' exist .

Magento - update handle

 Magento update handle

 1. For One Column
 <update handle="page_one_column" />

 2.  For Two Column left
 <update handle="page_two_columns_left" />

 3.  For Two Column right
 <update handle="page_two_columns_right" />

Thursday, May 21, 2015

Wordpress- How to use AJAX in WordPress

Wordpress- How to use AJAX in WordPress

STEP 1. Put the bellow code in your template file.

<a href="javascript:void(0)" id="click_to_ajax">Click Here to Ajax Request/response </a>
           
<script type="text/javascript">
var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";
</script>

<script type="text/javascript">
    jQuery(document).ready(function($) {   
    jQuery('#click_to_ajax').click(function() {
       
        var par1 = 'Banana';
        var par2 = 'Mango';
       
       jQuery.ajax({
            url: ajaxurl,
            data: {
                'action':'my_action_name',
                'par_1' : par1,
                'par_2' : par2,
            },
            success:function(data) {
              //console.log(data);
              alert(data);
            },
            error: function(errorThrown){
                //console.log(errorThrown);
                 alert('Something is wrong');
            }
        });     
       
    });
           
    });
</script>

STEP 2. Put the bellow code in functions.php in your theme file.

<?php
function my_ajax_callback_function()
{

    print_r($_REQUEST);
}
   
add_action( 'wp_ajax_my_action_name', 'my_ajax_callback_function' );    // If called from admin panel
add_action( 'wp_ajax_nopriv_my_action_name', 'my_ajax_callback_function' );    // If called from front end
?>

STEP 3. Be sure jquery libarary is included for the page. 


Njoy Your DaY :)

Tuesday, May 19, 2015

Ajax- Simple Form Post Example

Ajax- Simple Form Post Example

<form name="ajaxform" id="ajaxform" action="ajax-form-submit.php" method="POST">
First Name: <input type="text" name="fname" value =""/> <br/>
Last Name: <input type="text" name="lname" value ="" /> <br/>
Email : <input type="text" name="email" value=""/> <br/>
</form>
 
 
<script>
jQuery("#ajaxform").submit(function(e)
{
 var postData = jQuery(this).serializeArray();
 var formURL = jQuery(this).attr("action");
 jQuery.ajax(
 {
  url : formURL,
  type: "POST",
  data : postData,
  success:function(data, textStatus, jqXHR) 
  {

  },
  error: function(jqXHR, textStatus, errorThrown) 
  {
  }
 });
    e.preventDefault(); //STOP default action
}); 
</script> 
 
 
Note: Please be sure, jQuery libary has included for the page.

Njoy the day :) :)  

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/





Thursday, May 14, 2015

Wordpress- Login user programmatically

Wordpress- Login user  programmatically

         
function custom_login() {
 $creds = array();
 $creds['user_login'] = 'username here';
 $creds['user_password'] = 'password here';
 $creds['remember'] = true;
 $user = wp_signon( $creds, false );
 if ( is_wp_error($user) )
  echo $user->get_error_message();
}
// run it before the headers and cookies are sent
add_action( 'after_setup_theme', 'custom_login' );

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 - Get Current Currency Symbol

Magento : Get Current Currency Symbol

Code is useful for get currency symbol
 
     Mage::app()->getLocale()->currency(Mage::app()->getStore()->


     getCurrentCurrencyCode())->getSymbol()

or if you want to pass a certain currency code simply specify it:

     Mage::app()->getLocale()->currency('EUR')->getSymbol()

Magento - Get store Admin Email Address and Name

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

Magento- Remove index.php from url

If you want to access your magento URL without index.php
for example:
http://domain.com/index.php/category
to
http://domain.com/category
then use the following steps
1) Login to admin section by using the URL
http://domain.com/index.php/admin
2) then go to “System >>  Configuration >>Web >> Search Engines Optimization”
Use Web Server Rewrites : YES
3) Go to “System >>  Configuration >>Web >>Secure”
Use secure URL Frontend: YES
4)Then create the .htaccess file under your the magento installed folder.
If the magento installed under document root ( /home/username/public_html) then add follogig rules into .htaccess file
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

and If the magento installed under /shop or directory then add the following rules into ” /home/username/public_html/shop/.htaccess ” file.
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /shop/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /shop/index.php [L]
</IfModule>

Magento : Create extension package

Magento : Create extension package Click Here

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

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

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

Magento - 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 page layout from controller

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

Replace
$this->loadLayout();

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

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>

Sunday, May 3, 2015

Magento - Upload Image programmatically

if(isset($_FILES['image']['name']) and (file_exists($_FILES['image']['tmp_name']))) {
                try {
                    $uploader = new Varien_File_Uploader('image');
                    $uploader->setAllowedExtensions(array('jpg','jpeg','gif','png')); // or pdf or anything
                    $uploader->setAllowRenameFiles(false);
                    $uploader->setFilesDispersion(false);
                    $path = Mage::getBaseDir('media').'/netgoads/image/' ;      
                     $uploader->save($path, $_FILES['image']['name']);
                    $data['image'] = $_FILES['image']['name'];
                    }catch(Exception $e) {

                    }
                }

Friday, May 1, 2015

jQuery-Add/Remove Input Fields Dynamically with jQuery

<script>
jQuery(document).ready(function() {
    var max_fields      = 10; //maximum input boxes allowed
    var wrapper         = jQuery(".input_fields_wrap"); //Fields wrapper
    var add_button      = jQuery(".add_field_button"); //Add button ID
  
    var x = 1; //initlal text box count
    jQuery(add_button).click(function(e){ //on add input button click
        e.preventDefault();
        if(x < max_fields){ //max input box allowed
            x++; //text box increment
            jQuery(wrapper).append('<div><input type="text" name="mytext[]"/><a href="#" class="remove_field">Remove</a></div>'); //add input box
        }
    });
  
   jQuery(wrapper).on("click",".remove_field", function(e){ //user click on remove text
        e.preventDefault(); jQuery(this).parent('div').remove(); x--;
    })
});
 </script>
       
<div class="input_fields_wrap">
    <button class="add_field_button">Add More Fields</button>
    <div><input type="text" name="mytext[]"></div>
</div>

PHP- Create slug from string

<?php
function create_slug($string){
   $slug=preg_replace('/[^A-Za-z0-9-]+/', '-', $string);
   return $slug;
}
echo create_slug('does this thing work or not');
//returns 'does-this-thing-work-or-not'
?>