# Magento Code Snippets # ## Download extension manually using mage ## ```bash ./mage config-set preferred_state stable ./mage clear-cache ./mage sync ./mage download community Module_Name ``` ## Clear cache/reindex ## ```bash php -f shell/indexer.php reindexall ``` ```php removeCache('catalog_rules_dirty'); // reindex prices Mage::getModel('index/process')->load(2)->reindexEverything(); /* 1 = Product Attributes 2 = Product Attributes 3 = Catalog URL Rewrites 4 = Product Flat Data 5 = Category Flat Data 6 = Category Products 7 = Catalog Search Index 8 = Tag Aggregation Data 9 = Stock Status */ ?> ``` ## Delete cache/sessions/ ## ```bash rm -rf var/log/* rm -rf var/cache/* rm -rf var/session/* rm -rf var/report/* rm -rf var/locks/* rm -rf app/code/core/Zend/Cache ``` ## Load category by id ## ```php load(89); $_category_url = $_category->getUrl(); ?> ``` ## Load product by id or sku ## ```php load(12); $_product_2 = Mage::getModel('catalog/product')->loadByAttribute('sku','cordoba-classic-6-String-guitar'); ?> ``` ## Get Configurable product's Child products ## ```php getUsedProducts(null, $product); ?> ``` ## Get Configurable product's Children's (simple product) custom attributes ## ```php setProduct($_product); $col = $conf->getUsedProductCollection()->addAttributeToSelect('*')->addFilterByRequiredOptions(); foreach($col as $simple_product){ var_dump($simple_product->getId()); } ?> ``` ## Log to custom file ## ```php ``` ## Call Static Block ## ```php getLayout()->createBlock('cms/block')->setBlockId('block-name')->toHtml(); ?> ``` ## Add JavaScript to page ## First approach: page.xml - you can add something like ```xml ``` Second approach: Find `page/html/head.phtml` in your theme and add the code directly to `page.html`. Third approach: If you look at the stock page.html mentioned above, you'll see this line ```php getChildHtml(); ?> ``` Normally, the getChildHtml method is used to render a specific child block. However, if called with no paramater, getChildHtml will automatically render all the child blocks. That means you can add something like ```xml ... ``` to `page.xml`, and then add the `mytemplate.phtml` file. Any block added to the head block will be automatically rendered. (this automatic rendering doesn't apply for all layout blocks, only for blocks where getChildHtml is called without paramaters). ## Get the current category/product/cms page ## ```php ``` ## Run Magento Code Externally ## ```php ``` ## Programmatically change Magento’s core config data ## ```php saveConfig('design/head/demonotice', "1", 'default', 0); // turns notice off $my_change_config->saveConfig('design/head/demonotice', "0", 'default', 0); ?> ``` ## Changing the Admin URL ## Open up the `/app/etc/local.xml` file, locate the `` tag, and change the ‘admin’ part it to something a lot more random, eg: ```xml ``` Clear your cache and sessions. ## Magento: Mass Exclude/Unexclude Images ## By default, Magento will check the 'Exclude' box for you on all imported images, making them not show up as a thumbnail under the main product image on the product view. ```sql # Mass Unexclude UPDATE`catalog_product_entity_media_gallery_value` SET `disabled` = '0' WHERE `disabled` = '1'; # Mass Exclude UPDATE`catalog_product_entity_media_gallery_value` SET `disabled` = '1' WHERE `disabled` = '0'; ``` ## getBaseUrl – Magento URL Path ## ```php ``` ## Get The Root Category In Magento ## ```php getStore()->getRootCategoryId(); $_category = Mage::getModel('catalog/category')->load($rootCategoryId); // You can then get all of the top level categories using: $_subcategories = $_category->getChildrenCategories(); ?> ``` ## Get The Current URL In Magento ## ```php getCurrentUrl(); ?> ``` ## Category Navigation Listings in Magento ## Make sure the block that you’re working is of the type catalog/navigation. If you’re editing catalog/navigation/left.phtml then you should be okay. ```php
helper('catalog/category') ?> getStoreCategories() ?> 0): ?>
``` ## Debug using zend ## ```php ``` ## $_GET, $_POST & $_REQUEST Variables ## ```php getRequest()->getParam('product_id'); // The second parameter to getParam allows you to set a default value which is returned if the GET value isn't set $productId = Mage::app()->getRequest()->getParam('product_id', 44); $postData = Mage::app()->getRequest()->getPost(); // You can access individual variables like... $productId = $postData['product_id']); ?> ``` ## Get methods of an object ## First, use `get_class` to get the name of an object's class. ```php ``` Then, pass that `get_class_methods` to get a list of all the callable methods on an object ```php ``` ## Is product purchasable? ## ```php isSaleable()) { // do stuff } ?> ``` ## Load Products by Category ID ## ```php load(47); $_productCollection = $_category->getProductCollection(); if($_productCollection->count()) { foreach( $_productCollection as $_product ): echo $_product->getProductUrl(); echo $this->getPriceHtml($_product, true); echo $this->htmlEscape($_product->getName()); endforeach; } ?> ``` ## Get associated products In /app/design/frontend/default/site/template/catalog/product/view/type/ ``` php helper('catalog/output'); ?> getAllowProducts() ?>

productAttribute($_item, $_item->getName(), 'name'); ?> | getName(); ?> | getPrice(); ?>

``` ## Get An Array of Country Names/Codes in Magento ## ```php loadData() ->toOptionArray(false); echo '
';
    print_r( $countryList);
    exit('
'); ?> ``` ## Create a Country Drop Down in the Frontend of Magento ## ```php loadData() ->toOptionArray(false) ?> 0): ?> ``` ## Return Product Attributes ## ```php getThisattribute(); $_product->getAttributeText('thisattribute'); $_product->getResource()->getAttribute('thisattribute')->getFrontend()->getValue($_product); $_product->getData('thisattribute'); // The following returns the option IDs for an attribute that is a multiple-select field: $_product->getData('color'); // i.e. 456,499 // The following returns the attribute object, and instance of Mage_Catalog_Model_Resource_Eav_Attribute: $_product->getResource()->getAttribute('color'); // instance of Mage_Catalog_Model_Resource_Eav_Attribute // The following returns an array of the text values for the attribute: $_product->getAttributeText('color') // Array([0]=>'red', [1]=>'green') // The following returns the text for the attribute if ($attr = $_product->getResource()->getAttribute('color')): echo $attr->getFrontend()->getValue($_product); // will display: red, green endif; ?> ``` ## Cart Data ## ```php getQuote()->getData(); print_r($cart); $cart = Mage::helper('checkout/cart')->getCart()->getItemsCount(); print_r($cart); $session = Mage::getSingleton('checkout/session'); foreach ($session->getQuote()->getAllItems() as $item) { echo $item->getName(); Zend_Debug::dump($item->debug()); } ?> ``` ## Total items added in cart ## ```php getQuote()->getItemsCount(); Mage::getSingleton('checkout/session')->getQuote()->getItemsCount(); ?> ``` ## Total Quantity added in cart ## ```php getQuote()->getItemsQty(); Mage::getSingleton('checkout/session')->getQuote()->getItemsQty(); ?> ``` ## Sub Total for item added in cart ## ```php getQuote()->getSubtotal(); Mage::getSingleton('checkout/session')->getQuote()->getSubtotal(); ?> ``` ## Grand total for for item added in cart ## ```php getQuote()->getGrandTotal(); Mage::getSingleton('checkout/session')->getQuote()->getGrandTotal(); ?> ``` ## Sub total of cart inkl tax without shipping ## ```php getQuote(); $items = $quote->getAllItems(); foreach ($items as $item) { $priceInclVat = $item->getRowTotalInclTax(); } Mage::helper('checkout')->formatPrice($priceInclVat); ?> ``` ## Get Simple Products of a Configurable Product ## ```php getTypeId() == "configurable") { $ids = $_product->getTypeInstance()->getUsedProductIds(); ?>
    load($id); ?>
  • getName() . " - " . (int)Mage::getModel('cataloginventory/stock_item')->loadByProduct($simpleproduct)->getQty(); ?>
``` ## Reset Development Environment (delete orders, customers, reset ids and counters, truncate statistics) ## ```sql SET FOREIGN_KEY_CHECKS=0; -- Here's where we reset the orders TRUNCATE `sales_flat_order`; TRUNCATE `sales_flat_order_address`; TRUNCATE `sales_flat_order_grid`; TRUNCATE `sales_flat_order_item`; TRUNCATE `sales_flat_order_status_history`; TRUNCATE `sales_flat_quote`; TRUNCATE `sales_flat_quote_address`; TRUNCATE `sales_flat_quote_address_item`; TRUNCATE `sales_flat_quote_item`; TRUNCATE `sales_flat_quote_item_option`; TRUNCATE `sales_flat_order_payment`; TRUNCATE `sales_flat_quote_payment`; TRUNCATE `sales_flat_shipment`; TRUNCATE `sales_flat_shipment_item`; TRUNCATE `sales_flat_shipment_grid`; TRUNCATE `sales_flat_invoice`; TRUNCATE `sales_flat_invoice_grid`; TRUNCATE `sales_flat_invoice_item`; TRUNCATE `sendfriend_log`; TRUNCATE `tag`; TRUNCATE `tag_relation`; TRUNCATE `tag_summary`; TRUNCATE `wishlist`; TRUNCATE `log_quote`; TRUNCATE `report_event`; ALTER TABLE `sales_flat_order` AUTO_INCREMENT=1; ALTER TABLE `sales_flat_order_address` AUTO_INCREMENT=1; ALTER TABLE `sales_flat_order_grid` AUTO_INCREMENT=1; ALTER TABLE `sales_flat_order_item` AUTO_INCREMENT=1; ALTER TABLE `sales_flat_order_status_history` AUTO_INCREMENT=1; ALTER TABLE `sales_flat_quote` AUTO_INCREMENT=1; ALTER TABLE `sales_flat_quote_address` AUTO_INCREMENT=1; ALTER TABLE `sales_flat_quote_address_item` AUTO_INCREMENT=1; ALTER TABLE `sales_flat_quote_item` AUTO_INCREMENT=1; ALTER TABLE `sales_flat_quote_item_option` AUTO_INCREMENT=1; ALTER TABLE `sendfriend_log` AUTO_INCREMENT=1; ALTER TABLE `sales_flat_order_payment` AUTO_INCREMENT=1; ALTER TABLE `sales_flat_quote_payment` AUTO_INCREMENT=1; ALTER TABLE `sales_flat_shipment` AUTO_INCREMENT=1; ALTER TABLE `sales_flat_shipment_item` AUTO_INCREMENT=1; ALTER TABLE `sales_flat_invoice` AUTO_INCREMENT=1; ALTER TABLE `sales_flat_invoice_grid` AUTO_INCREMENT=1; ALTER TABLE `sales_flat_invoice_item` AUTO_INCREMENT=1; ALTER TABLE `sales_flat_shipment_grid` AUTO_INCREMENT=1; ALTER TABLE `tag` AUTO_INCREMENT=1; ALTER TABLE `tag_relation` AUTO_INCREMENT=1; ALTER TABLE `tag_summary` AUTO_INCREMENT=1; ALTER TABLE `wishlist` AUTO_INCREMENT=1; ALTER TABLE `log_quote` AUTO_INCREMENT=1; ALTER TABLE `report_event` AUTO_INCREMENT=1; -- Here's where we reset the customers TRUNCATE `customer_address_entity`; TRUNCATE `customer_address_entity_datetime`; TRUNCATE `customer_address_entity_decimal`; TRUNCATE `customer_address_entity_int`; TRUNCATE `customer_address_entity_text`; TRUNCATE `customer_address_entity_varchar`; TRUNCATE `customer_entity`; TRUNCATE `customer_entity_datetime`; TRUNCATE `customer_entity_decimal`; TRUNCATE `customer_entity_int`; TRUNCATE `customer_entity_text`; TRUNCATE `customer_entity_varchar`; TRUNCATE `log_customer`; TRUNCATE `log_visitor`; TRUNCATE `log_visitor_info`; ALTER TABLE `customer_address_entity` AUTO_INCREMENT=1; ALTER TABLE `customer_address_entity_datetime` AUTO_INCREMENT=1; ALTER TABLE `customer_address_entity_decimal` AUTO_INCREMENT=1; ALTER TABLE `customer_address_entity_int` AUTO_INCREMENT=1; ALTER TABLE `customer_address_entity_text` AUTO_INCREMENT=1; ALTER TABLE `customer_address_entity_varchar` AUTO_INCREMENT=1; ALTER TABLE `customer_entity` AUTO_INCREMENT=1; ALTER TABLE `customer_entity_datetime` AUTO_INCREMENT=1; ALTER TABLE `customer_entity_decimal` AUTO_INCREMENT=1; ALTER TABLE `customer_entity_int` AUTO_INCREMENT=1; ALTER TABLE `customer_entity_text` AUTO_INCREMENT=1; ALTER TABLE `customer_entity_varchar` AUTO_INCREMENT=1; ALTER TABLE `log_customer` AUTO_INCREMENT=1; ALTER TABLE `log_visitor` AUTO_INCREMENT=1; ALTER TABLE `log_visitor_info` AUTO_INCREMENT=1; -- This is to Reset all the ID counters TRUNCATE `eav_entity_store`; ALTER TABLE `eav_entity_store` AUTO_INCREMENT=1; SET FOREIGN_KEY_CHECKS=1; TRUNCATE TABLE `sales_bestsellers_aggregated_daily`; TRUNCATE TABLE `sales_bestsellers_aggregated_monthly`; TRUNCATE TABLE `sales_bestsellers_aggregated_yearly`; DELETE FROM report_event WHERE event_type_id IN (SELECT event_type_id FROM report_event_types WHERE event_name IN ('catalog_product_view')); ``` ## Update all subscribers into a customer group (e.g. 5) ## ```sql UPDATE customer_entity, newsletter_subscriber SET customer_entity.`group_id` = 5 WHERE customer_entity.`entity_id` = newsletter_subscriber.`customer_id` AND newsletter_subscriber.`subscriber_status` = 1; ``` ## Setting file permissions ## ```bash find -type f \-exec chmod 644 {} \; find -type d \-exec chmod 755 {} \; ``` Other recommendations in "Securing Magento File & Directory Permissions" (http://blog.nexcess.net/2010/12/06/securing-magento-file-directory-permissions/) ```bash find \-exec chown youruser.youruser {} \; find -type f \-exec chmod 644 {} \; find -type d \-exec chmod 711 {} \; find -type f -name "*.php" \-exec chmod 600 {} \; chmod 600 /app/etc/*.xml ``` ## Getting Configurable Product from Simple Product ID in Magento 1.5+ ## ```php getParentIdsByChild($simpleProductId); $product = Mage::getModel('catalog/product')->load($parentIds[0]); echo $product->getId(); // ID = 462 (aka, Parent of 465) ?> ``` ## Check if customer is logged in ## ```php isLoggedIn(); if ($_customer) {} ?> ``` ## Get product image ## ```php helper('catalog/image')->init($_product, 'image'); ?> ``` ## Show image using current skin path (PHTML) ## ```html logo ``` ## Show image using current skin path (CMS) ## ```html ``` ## Show CMS block (PHTML) ## ```php getLayout()->createBlock('cms/block')->setBlockId('my_block_identifier')->toHtml(); ?> ```