Tuesday 4 November 2014

How to add a product to cart through parameters in url in magento

Hi sometime we need to add the product to cart by passing parameters to the url without actual adding to cart through default process. Fortunately we can do this in magento very easily.

Here is how we can do this


For simple product

www.yoursite.com/checkout/cart/add?product=[id]&qty=[qty]
 
id = your product id 
qty = number od items you ned to add to cart //  eg 1 , 2 or 3 
 
 


For simple product with custom optionss
 
http://magentoserver.com/checkout/cart/add?product=13&
qty=1&options[12]=57 
 

You can get the options id and value by viewing the source of the simple product page and it’s dropdowns.

By SKU

To add a product by SKU we must first instantiate an instance of the Mage::app() outside of the present application. You can do this as such:
  1. <?php
  2. include_once 'app/Mage.php';
  3. Mage::app();
  4. Mage::getSingleton('core/session', array('name' => 'frontend'));
By adding a $_GET variable we can get the sku and use an instance of the Product model to get the Magento ID for us.
  1. $cProd = Mage::getModel('catalog/product');
  2. $id = $cProd->getIdBySku("$sku");
Now that we have our ID we can do something useful with it - such as add it to the cart with the default of 1 product as the quantity. You can use other $_GET variables and conditions to simulate the adding of the quanitity to the querystring using the PHP Header Redirect:
  1. header('Location: '. Mage::getUrl('checkout/cart/add', array('product' => $id)));



For bundle product 





The standard URL format for adding a bundle item to the cart via URL is as such:
/path/to/app/checkout/cart/add/product/[id]/?bundle_option
[[option_id]][]=[selection_id]

  1. $w = Mage::getSingleton('core/resource')->getConnection('core_write');
  2. $result = $w->query("select `option_id`, `selection_id` from `catalog_product_bundle_selection` where `parent_product_id`=$id");

his will provide us with our dataset. Using PDO and looping for each individual SKU inside of a given bundle ID we find that the following code will build the parameters for the cart add and then redirect to it:

$_product = Mage::getModel('catalog/product')->load($id);

if ($_product->getTypeId() == 'bundle') {
$w = Mage::getSingleton('core/resource')->getConnection('core_write');
$result = $w->query("select `option_id`, `selection_id` from `catalog_product_bundle_selection` where `parent_product_id`=$id");
$route = "checkout/cart/add";
$params = array('product' => $id);
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
$params['bundle_option['. $row[option_id] .']'][] = $row['selection_id'];
};

header("Location: ". Mage::getUrl($route, $params));
}    

www.your_domain.com/checkout/cart/add?product=68&qty=1&super_attribute[528]=55&super_attribute[525]=56




For configurable product
http://www.your_domain.com/checkout/cart/add?product=68&qty=1&
super_attribute[528]=55&supe
r_attribute[525]=56
 
 
 

 
Hope this will help .thanks :)



Tuesday 3 June 2014

show product review oin custom list page Magento

HI there are some times we need to make the own list pages of products . in that the review doesnot show on them . To show reviews on them use below code



1) if you intend to display the average rating of each product, add this helper method inside the page(like list.phtml):
 

<?php
$storeId = Mage::app()->getStore()->getId();
$summaryData = Mage::getModel('review/review_summary')->setStoreId($storeId)  ->load($_product->getId());
?>                                                                          
// Rating Percentage showing of a product
<div class="rating">(<?php echo $summaryData['rating_summary']; ?>%)</div>   
 
2) Get the product Review anywhere in magento


<?php // review of a product at any page
$_reviews = Mage::getModel('review/review')->getResourceCollection();
$_reviews->addStoreFilter( Mage::app()->getStore()->getId() )
->addEntityFilter('product', $product->getId())
->addStatusFilter( Mage_Review_Model_Review::STATUS_APPROVED )
->setDateOrder()
->addRateVotes();
$avg = 0;
$ratings = array();
if (count($_reviews) > 0){
foreach ($_reviews->getItems() as $_review): ?>
<?php foreach( $_review->getRatingVotes() as $_vote ): ?>
<?php $ratings[] = $_vote->getPercent(); ?>
<?php endforeach; ?>
<?php endforeach;
$avg = array_sum($ratings)/count($ratings); }
?>
<?php if($avg > 0):?>
<div class=”ratings”>
<div class=”rating-box”>
<div class=”rating” style=”width: <?php echo ceil($avg) ; ?>%;”></div>
</div>
</div>
<?php endif;?>
3) Get the Review Count of a product in any page like list.phtml

<?php                                                                         // review count of a product
echo $reviewCount = $_product->getRatingSummary()->getReviewsCount() ? $_product->getRatingSummary()->getReviewsCount(): 0;
?>

Tuesday 27 May 2014

Get cart details in Magento

You can get the cart details with the following code

<?php
$cart = Mage::getModel('checkout/cart')->getQuote(); //to get cart detail
foreach ($cart->getAllItems() as $item) {
   echo  $productId = $item->getProduct()->getId(); // product id in cart
   echo $productPrice = $item->getProduct()->getPrice(); // product price in cart
$product = Mage::getModel('catalog/product')->load($productId); // load product to get all details of product
//load the categories of this product
$categoryCollection = $product->getCategoryCollection();
$catIds = $product->getCategoryIds(); // to get all category ids of products in cart
$catCollection = Mage::getResourceModel('catalog/category_collection')  // to get all all details of categories of products in cart
                     //->addAttributeToSelect('name')
                     //->addAttributeToSelect('url')
                     ->addAttributeToSelect('*')
                     ->addAttributeToFilter('entity_id', $catIds)
                     ->addIsActiveFilter();

foreach($catCollection as $cat){
 // print_r($cat->getData());
 $catname[] =  $cat->getName();
  //echo $cat->getUrl();
}

}
print_r($catname); //category names array
?>

Friday 23 May 2014

import product image from external url in magento 1.8

Hi in some project i need to import the csv of products in that i have he values of product images is like

http://www.example.com/image.jpg

i need to import that by default there is no mechanism in magento to import external image.

for doinmg this we have to edit the import function in below file

app/code/core/Mage/Catalog/Model/Convert/Adapter/Product.php

around line 754 you will see some code like this

  foreach ($product->getMediaAttributes() as $mediaAttributeCode => $mediaAttribute) {
             if (isset($importData[$mediaAttributeCode])) {
                 $file = trim($importData[$mediaAttributeCode]);
                 if (!empty($file) && !$mediaGalleryBackendModel->getImage($product, $file)) {
                    $arrayToMassAdd[] = array('file' => trim($file), 'mediaAttribute' => $mediaAttributeCode);
                 }
            }
         }


you simply need to replace this dunction with the below one 

foreach ($product->getMediaAttributes() as $mediaAttributeCode => $mediaAttribute) {
                        if (isset($importData[$mediaAttributeCode])) {
                            $file = trim($importData[$mediaAttributeCode]);
                            if (!empty($file) && !$mediaGalleryBackendModel->getImage($product, $file)) {
                                // Start Of Code To Import Images From Urls
                                if (preg_match('%http?://[a-z0-9\-./]+\.(?:jpe?g|png|gif)%i', $file)) {
                                    $path_parts = pathinfo($file);
                                    $html_filename = DS . $path_parts['basename'];
                                    $fullpath = Mage::getBaseDir('media') . DS . 'import' . $html_filename;
                                    if(!file_exists($fullpath)) {
                                        file_put_contents($fullpath, file_get_contents($file));}
                                    $arrayToMassAdd[] = array('file' => trim($html_filename), 'mediaAttribute' => $mediaAttributeCode);
                                }
                                else
                                {
                                    $arrayToMassAdd[] = array('file' => trim($file), 'mediaAttribute' => $mediaAttributeCode);
                                }
                                // End Of Code To Import Images From URLs
                            }
                        }
                        }

Hope this will help you. thanks





Tuesday 20 May 2014

Get current product data in custom file in magento

HI in some project i need to develop a module through which i need to insert a newly created product attribute  on product page with the modue xml file . For that i need to havethe current product data in my module file.

for that i have use the below function

$product_id = Mage::registry('current_product')->getId(); 
 
with this when your file will include in the porduct view page.it will load
 product id from your file.You can get any value from this.

Tuesday 13 May 2014

How to check url contains http or htttps in php

Hi with the following code you can get the protocol of the server  
 
 
 
if (isset($_SERVER['HTTPS']) &&
    ($_SERVER['HTTPS'] == 'on' || $_SERVER['HTTPS'] == 1) ||
    isset($_SERVER['HTTP_X_FORWARDED_PROTO']) &&
    $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') {
  $protocol = 'https://';
}
else {
  $protocol = 'http://';
}

Wednesday 16 April 2014

Get all images tags from the remote url through php

In some project i need to get all image tags from the remote url
I have google a lot but not getting any particular solution.
But atlast i got a very good code which works like a charm

you can find that code on

https://docs.google.com/file/d/0B9cbYvYQ9b0YY2xxUW5kUms0NWM/edit

in this file you will see the below code at very last of file


// Create DOM from URL or file
$html = file_get_html('https://www.google.co.in/'); // replace your url

// Find all images
foreach($html->find('img') as $element) // to get all image src  from the url
       echo $element->src . '<br>';

// Find all links
foreach($html->find('a') as $element) // to get all anchor tags  from the url
       echo $element->href . '<br>';


with this script you can get any paramaeter from the remote url.  Remember to copy the full file from the downlaod file from here






      

Wednesday 9 April 2014

Show popular search terms in sidebar Magento

Hi in some project i need to show the popular search terms in the sidebar . For that i have use the following code


  <reference name="right">
            <!-- Search Terms -->
            <block type="catalogsearch/term" after="cart.sidebar" name="catalogsearch.term" template="catalogsearch/term.phtml"/>
        </reference>


you can place this code in the  catalog.xml file of your theme

Friday 7 March 2014

Move Magento from one server to another


Hi You can easily  move Magento website from one server to another server in 3 very easy steps.

1. Delete the content of the folder /var   // it contains cache and session files dont worry about this just delete this

2. Change the values of the file /app/etc/local.xml There you can find your connection string data (database user, host and name).

3. Once you got your database uploaded, you need to make some changes.
Run this query:
You gonna get something like this:
Now, change that values for your new url, run below query.
If you run the first query, now you gonna get something like this:

PgSQL
1
2
3
4
5
6
+-----------+---------+----------+-----------------------+------------------------------+
| config_id | scope   | scope_id | path                  | value                        |
+-----------+---------+----------+-----------------------+------------------------------+
|         2 | default |        0 | web/unsecure/base_url | http://www.somedomain.com/ |
|         3 | default |        0 | web/secure/base_url   | http://www.somedomain.com/ |
+-----------+---------+----------+-----------------------+------------------------------+

Saturday 8 February 2014

delete all products data from database Magento

SET FOREIGN_KEY_CHECKS = 0;
TRUNCATE TABLE `catalog_product_bundle_option`;
TRUNCATE TABLE `catalog_product_bundle_option_value`;
TRUNCATE TABLE `catalog_product_bundle_selection`;
TRUNCATE TABLE `catalog_product_entity_datetime`;
TRUNCATE TABLE `catalog_product_entity_decimal`;
TRUNCATE TABLE `catalog_product_entity_gallery`;
TRUNCATE TABLE `catalog_product_entity_int`;
TRUNCATE TABLE `catalog_product_entity_media_gallery`;
TRUNCATE TABLE `catalog_product_entity_media_gallery_value`;
TRUNCATE TABLE `catalog_product_entity_text`;
TRUNCATE TABLE `catalog_product_entity_tier_price`;
TRUNCATE TABLE `catalog_product_entity_varchar`;
TRUNCATE TABLE `catalog_product_link`;
TRUNCATE TABLE `catalog_product_link_attribute`;
TRUNCATE TABLE `catalog_product_link_attribute_decimal`;
TRUNCATE TABLE `catalog_product_link_attribute_int`;
TRUNCATE TABLE `catalog_product_link_attribute_varchar`;
TRUNCATE TABLE `catalog_product_link_type`;
TRUNCATE TABLE `catalog_product_option`;
TRUNCATE TABLE `catalog_product_option_price`;
TRUNCATE TABLE `catalog_product_option_title`;
TRUNCATE TABLE `catalog_product_option_type_price`;
TRUNCATE TABLE `catalog_product_option_type_title`;
TRUNCATE TABLE `catalog_product_option_type_value`;
TRUNCATE TABLE `catalog_product_super_attribute_label`;
TRUNCATE TABLE `catalog_product_super_attribute_pricing`;
TRUNCATE TABLE `catalog_product_super_attribute`;
TRUNCATE TABLE `catalog_product_super_link`;
TRUNCATE TABLE `catalog_product_enabled_index`;
TRUNCATE TABLE `catalog_product_website`;
TRUNCATE TABLE `catalog_category_product_index`;
TRUNCATE TABLE `catalog_category_product`;
TRUNCATE TABLE `cataloginventory_stock_item`;
TRUNCATE TABLE `cataloginventory_stock_status`;
TRUNCATE TABLE `cataloginventory_stock`;
INSERT  INTO `catalog_product_link_type`(`link_type_id`,`code`) VALUES (1,'relation'),(2,'bundle'),(3,'super'),(4,'up_sell'),(5,'cross_sell');
INSERT  INTO `catalog_product_link_attribute`(`product_link_attribute_id`,`link_type_id`,`product_link_attribute_code`,`data_type`) VALUES (1,2,'qty','decimal'),(2,1,'position','int'),(3,4,'position','int'),(4,5,'position','int'),(6,1,'qty','decimal'),(7,3,'position','int'),(8,3,'qty','decimal');
INSERT  INTO `cataloginventory_stock`(`stock_id`,`stock_name`) VALUES (1,'Default');
TRUNCATE TABLE `catalog_product_entity`;
SET FOREIGN_KEY_CHECKS = 1;

adding customer address attributes in Magento

Hi in some project i need to add the new address field in magento billing and shipping forms .i have tried so much on google and i found so many links and try them but no one was working fine than atlast i got the below link at it works as a charm for me


http://indiestechtips.wordpress.com/2011/07/30/how-to-add-custom-field-in-the-billing-and-shipping-address-of-onepage-checkout-in-magento/

Friday 7 February 2014

Get all customer data in Magento programatically

 with the below piece of code you will be able to load all data of all users with there address and all other information


<?php
$customer_email = "rhtgoel7@gmail.com";
$customer = Mage::getModel("customer/customer")->getCollection()->load();
echo"<pre>";
$custdata = $customer->getData();
foreach($custdata as $custdata1 ) {
//print_r($custdata1);
$custemail[] = $custdata1['email'];
}
print_r($custemail);
$customer_email = "rhtgoel7@gmail.com";
foreach( $custemail as $custemail1 ) {
$customer = Mage::getModel("customer/customer");
$customer->setWebsiteId(Mage::app()->getWebsite()->getId());
$customer->loadByEmail($custemail1); //load customer by email id
//use
echo $customer->getId();
echo $customer->getFirstName();
print_r($customer->getData());

}
?>