Skip to content

Instantly share code, notes, and snippets.

@gelanivishal
Last active September 26, 2023 07:57
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save gelanivishal/3f4cbaa54e7c42b56357 to your computer and use it in GitHub Desktop.
Save gelanivishal/3f4cbaa54e7c42b56357 to your computer and use it in GitHub Desktop.

Magento Tips, Tricks and Snippets

Extensions

Helpful Urls

Caching

Clear cache/reindex

<?php
// clear cache
Mage::app()->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
*/

// Recreate a single index programmatically
Mage::getModel('index/process')->load(Mage_Catalog_Helper_Product_Flat::CATALOG_FLAT_PROCESS_CODE, 'indexer_code')->reindexEverything();
?>

Categories and Products

Load category by id

<?php
$_category = Mage::getModel('catalog/category')->load(89);
$_category_url = $_category->getUrl();
?>

Load product by id or sku

<?php
$_product_1 = Mage::getModel('catalog/product')->load(12);
$_product_2 = Mage::getModel('catalog/product')->loadByAttribute('sku','cordoba-classic-6-String-guitar');
?>

Get Configurable product's Child products

<?php
// input is $_product and result is iterating child products
$childProducts = Mage::getModel('catalog/product_type_configurable')->getUsedProducts(null, $product);
?>

Get Configurable product's Children's (simple product) custom attributes

<?php
// input is $_product and result is iterating child products
$conf = Mage::getModel('catalog/product_type_configurable')->setProduct($_product);
$col = $conf->getUsedProductCollection()->addAttributeToSelect('*')->addFilterByRequiredOptions();
foreach($col as $simple_product){
    var_dump($simple_product->getId());
}
?>

Is product purchasable?

<?php if($_product->isSaleable()) { // do stuff } ?>

Load Products by Category ID

<?php
$_category = Mage::getModel('catalog/category')->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 The Root Category

<?php
$rootCategoryId = Mage::app()->getStore()->getRootCategoryId();
$_category = Mage::getModel('catalog/category')->load($rootCategoryId);
// You can then get all of the top level categories using:
$_subcategories = $_category->getChildrenCategories();
?>

Return Product Attributes

<?php
$_product->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;
?>

Get Simple Products of a Configurable Product

<?php
if($_product->getTypeId() == "configurable") {
    $ids = $_product->getTypeInstance()->getUsedProductIds();
?>
<ul>
    <?php
    foreach ($ids as $id) {
        $simpleproduct = Mage::getModel('catalog/product')->load($id);
    ?>
        <li>
            <?php
            echo $simpleproduct->getName() . " - " . (int)Mage::getModel('cataloginventory/stock_item')->loadByProduct($simpleproduct)->getQty();
            ?>
        </li>               
    <?php
    }
    ?>
</ul>
<?php
}
?>

Getting Configurable Product from Simple Product ID in Magento 1.5+

<?php
$simpleProductId = 465;
$parentIds = Mage::getResourceSingleton('catalog/product_type_configurable')
    ->getParentIdsByChild($simpleProductId);
$product = Mage::getModel('catalog/product')->load($parentIds[0]);
echo $product->getId(); // ID = 462 (aka, Parent of 465)

# Generate URL to variant of configurable by $sku
$simple = Mage::getModel('catalog/product')->loadByAttribute('sku', $sku);
$productId = array_shift(Mage::getModel('catalog/product_type_configurable')->getParentIdsByChild($simple->getId()));
$url = Mage::getUrl('catalog/product/view', array( 'id' => $productId, 'option_id' => $simple->getVariant() ));

?>

Get the current category/product/cms page

<?php
$currentCategory = Mage::registry('current_category');
$currentProduct = Mage::registry('current_product');
$currentCmsPage = Mage::registry('cms_page');
?>

Get original image url/path of product and Category

// Product
$productId = 'SOME_PRODUCT_ID';
$product = Mage::getModel('catalog/product')->load($productId);

$productMediaConfig = Mage::getModel('catalog/product_media_config');
$baseImageUrl = $productMediaConfig->getMediaUrl($product->getImage());
$smallImageUrl = $productMediaConfig->getMediaUrl($product->getSmallImage());
$thumbnailUrl = $productMediaConfig->getMediaUrl($product->getThumbnail());

echo Mage::helper('catalog/image')->init($product, 'image')->resize(400,400);
echo Mage::helper('catalog/image')->init($_product, 'thumbnail')->resize(168);
echo Mage::helper('catalog/image')->init($_product, 'small_image')->resize(168);

// Category 
$_category  = $this->getCurrentCategory();
// <img src="<?php echo Mage::getBaseUrl('media').'catalog/category/'.$_category->getThumbnail()  ?>" />

Magento get Category and it's sub category

<?php
$category = Mage::getSingleton('catalog/layer')->getCurrentCategory();
$categories = $category->getCollection()
    ->addAttributeToSelect(array('name', 'thumbnail'))
    ->addAttributeToFilter('is_active', 1)
    ->addIdFilter($category->getChildren())
?>
<ul class="subcategories">
    <?php foreach ($categories as $category): ?>
        <li>
            <a href="<?php echo $category->getUrl() ?>"><img
                    src="<?php echo Mage::getBaseUrl('media') . 'catalog' . DS . 'category' . DS . $category->getThumbnail() ?>"
                    alt="<?php echo $this->htmlEscape($category->getName()) ?>"/>
                <span><?php echo $category->getName() ?></span></a>
        </li>
    <?php endforeach; ?>
</ul>

// To only one category
<?php 
$category = Mage::getModel('catalog/category')->load(4);
$subcategories = $category->getChildrenCategories();
if (count($subcategories) > 0){
    echo $category->getName();
    foreach($subcategories as $subcategory){
         echo $subcategory->getName();
    }
}
?>

Custom Collection to join with attribute

<?php
collection = Mage::getModel('anybooking/anybooking')->getCollection()
        ->addFieldToFilter('order_status', '1');
$this->setCollection($collection);

$attribute = Mage::getSingleton('eav/config')
    ->getAttribute(Mage_Catalog_Model_Product::ENTITY, 'userid');

$collection->getSelect()->joinLeft(
    array('userid_table' => $attribute->getBackendTable()),
    "main_table.entity_id = userid_table.entity_id AND userid_table.attribute_id={$attribute->getId()}",
    array('userid' => 'value')
);
?>```

### Get category name of current product ###

```php
$categoryIds = $_product->getCategoryIds();
if(count($categoryIds) ){
     $firstCategoryId = $categoryIds[0];
     $_category = Mage::getModel('catalog/category')->load($firstCategoryId);

     echo $_category->getName();
}

Blocks

Call Static Block

<?php if(Mage::getModel('cms/block')->load('static_block_identifier')->getIsActive()): ?>
    <?php echo $this->getLayout()->createBlock('cms/block')->setBlockId('block-name')->toHtml(); ?>
<?php endif; ?>
{{block type="core/template" name="test" template="cms/startseite.phtml"}}

Customer handling

Check if customer is logged in

<?php $logged_in = Mage::getSingleton('customer/session')->isLoggedIn(); // (boolean) ?>
$customer_data=Mage::getSingleton('customer/session')->getCustomer();

Update all subscribers into a customer group (e.g. 5)

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;

Get An Array of Country Names/Codes in Magento

<?php
// Get An Array of Country Names/Codes in Magento
$countryList = Mage::getResourceModel('directory/country_collection')
                    ->loadData()
                    ->toOptionArray(false);
     
    echo '<pre>';
    print_r( $countryList);
    exit('</pre>');

// Create a Country Drop Down in the Frontend of Magento
$countryList = Mage::getResourceModel('directory/country_collection')
                    ->loadData()
                    ->toOptionArray(false);

    <?php if (count($_countries) > 0): ?>
    <select name="country" id="country">
        <option value="">-- Please Select --</option>
        <?php foreach($_countries as $_country): ?>
            <option value="<?php echo $_country['value'] ?>">
                <?php echo $_country['label'] ?>
            </option>
        <?php endforeach; ?>
    </select>
<?php endif; ?>
<?php
// Create a Country Drop Down in the Magento Admin
    $fieldset->addField('country', 'select', array(
        'name'  => 'country',
        'label'     => 'Country',
        'values'    => Mage::getModel('adminhtml/system_config_source_country')->toOptionArray(),
    ));
?>

Logging and Exception handling

Log to custom file

<?php Mage::log('Your Log Message', Zend_Log::INFO, 'your_log_file.log'); ?>

Send success / errors to session

<?php 
// Showing messages on the frontend
$message = 'Your message ... ';
Mage::getSingleton('core/session')->addError($message);
Mage::getSingleton('core/session')->addSuccess($message);
// Showing messages in the admin
$message = 'Your message ... ';
Mage::getSingleton(adminhtml/session')->addError($message);
Mage::getSingleton('adminhtml/session')->addSuccess($message);
// Code to show notice in the frontend
Mage::getSingleton('core/session')->addNotice($message);
?>

Configuration

Programmatically change or read Magento’s core config data

<?php
// find 'path' in table 'core_config_data' e.g. 'design/head/demonotice'
$my_change_config = new Mage_Core_Model_Config();
// turns notice on
$my_change_config->saveConfig('design/head/demonotice', "1", 'default', 0);
// turns notice off
$my_change_config->saveConfig('design/head/demonotice', "0", 'default', 0);

// Read data
$mailTemplateId = Mage::getStoreConfig('YOUR/PATH/HERE', $storeId);
?>

Changing the Admin URL

Open up the /app/etc/local.xml file, locate the <frontName> tag, and change the ‘admin’ part it to something a lot more random, eg:

<frontName><![CDATA[supersecret-admin-name]]></frontName>

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.

# 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';

Turn template hints on/off via database

UPDATE
`core_config_data`
SET
`value` = 0
WHERE
`path` = "dev/debug/template_hints"
OR
`path` = "dev/debug/template_hints_blocks";

Delete all products

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_decimal`;
TRUNCATE TABLE `catalog_product_link_attribute_int`;
TRUNCATE TABLE `catalog_product_link_attribute_varchar`;
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`;
TRUNCATE TABLE `catalog_product_super_attribute_label`;
TRUNCATE TABLE `catalog_product_super_attribute_pricing`;
TRUNCATE TABLE `catalog_product_super_link`;
TRUNCATE TABLE `catalog_product_enabled_index`;
TRUNCATE TABLE `catalog_product_website`;
TRUNCATE TABLE `catalog_product_entity`;
TRUNCATE TABLE `cataloginventory_stock_item`;
TRUNCATE TABLE `cataloginventory_stock_status`;

Get An Array of Country Names/Codes in Magento

<?php
$countryList = Mage::getResourceModel('directory/country_collection')
                    ->loadData()
                    ->toOptionArray(false);
     
    echo '<pre>';
    print_r( $countryList);
    exit('</pre>');
?>

Create a Country Drop Down in the Frontend of Magento

<?php
$_countries = Mage::getResourceModel('directory/country_collection')
                                    ->loadData()
                                    ->toOptionArray(false) ?>
<?php if (count($_countries) > 0): ?>
    <select name="country" id="country">
        <option value="">-- Please Select --</option>
        <?php foreach($_countries as $_country): ?>
            <option value="<?php echo $_country['value'] ?>">
                <?php echo $_country['label'] ?>
            </option>
        <?php endforeach; ?>
    </select>
<?php endif; ?>

Create a Country Drop Down in the Magento Admin

<?php
    $fieldset->addField('country', 'select', array(
        'name'  => 'country',
        'label'     => 'Country',
        'values'    => Mage::getModel('adminhtml/system_config_source_country')->toOptionArray(),
    ));
?>

Cart Data

<?php
$cart = Mage::getModel('checkout/cart')->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());
}
?>

URLs, Requests and Responses

$_GET, $_POST & $_REQUEST Variables

<?php
// $_GET
$productId = Mage::app()->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']);
?>

Redirecting to other location

<?php
$target = 'http://klein0r.de';
Mage::app()->getFrontController()->getResponse()->setRedirect($target)->sendResponse();
exit;
?>

To check which event occur

//app/Mage.php
public static function dispatchEvent($name, array $data = array())
{
   Mage::log('EventName: '.$name,null,'events.log',true);
   Varien_Profiler::start('DISPATCH EVENT:'.$name);
   $result = self::app()->dispatchEvent($name, $data);
   Varien_Profiler::stop('DISPATCH EVENT:'.$name);
   return $result;
}

Get The Current URL In Magento

<?php echo Mage::helper('core/url')->getCurrentUrl(); ?>

Get Magento locale date/time from GMT timestamp / current time

date("Y-m-d", Mage::getModel('core/date')->timestamp(time()));
//OR
Mage::getModel('core/date')->date('Y-m-d H:i:s');

Magento : Get Base Url , Skin Url , Media Url , Js Url , Store Url and Current Url

<?php
// http://example.com/
echo Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB);
echo Mage::getBaseUrl();
// Get Store Url without index.php 
echo Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB)

// http://example.com/js/
echo Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_JS);

// http://example.com/index.php/
echo Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_LINK);

// http://example.com/media/
echo Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA);

// http://example.com/skin/
echo Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_SKIN);
// Unsecure Skin Url
$this->getSkinUrl('images/imagename.jpg');
// Secure Skin Url
$this->getSkinUrl('images/imagename.gif', array('_secure'=>true));

//Get Current Url
echo Mage::helper('core/url')->getCurrentUrl();


Get Url in cms pages or static blocks
Get Base Url : {{store url=""}}
Get Skin Url : {{skin url='images/imagename.jpg'}}
Get Media Url : {{media url='/imagename.jpg'}}
Get Store Url : {{store url='mypage.html'}}
Get Store Url without index.php : {{config path = "web/unsecure/baseurl"}}
?>

Get Store, Storeview and Website Detail

<?php
// store's details
echo $store = Mage::app()->getStore();
// store's id
echo $storeId = Mage::app()->getStore()->getStoreId();
// store's code
echo $storeCode = Mage::app()->getStore()->getCode();
// website's id
echo $websiteId = Mage::app()->getStore()->getWebsiteId();
// store's group id
echo $storeGroupId = Mage::app()->getStore()->getGroupId();
// store's name
echo $storeName = Mage::app()->getStore()->getName();
// website's code 
echo $websitecode = Mage::app()->getWebsite()->getCode();
// store's sort order
echo $storeSortOrder = Mage::app()->getStore()->getSortOrder();
// store's status 
echo $storeIsActive = Mage::app()->getStore()->getIsActive();
// store's locale 
echo $storeLocaleCode = Mage::app()->getStore()->getLocaleCode();
// store's home url
echo $storeHomeUrl = Mage::app()->getStore()->getHomeUrl();

Current store currency details – currency code, currency symbol, currency name

<?php
// store currency code eg. USD, INR
$currency_code = Mage::app()->getStore()->getCurrentCurrencyCode();

// store currency symbol eg. $
$currency_symbol = Mage::app()->getLocale()->currency( $currency_code )->getSymbol();

// store currency name eg. Indian Rupee
$currency_name = Mage::app()->getLocale()->currency( $currency_code )->getName();
?>

Get the current date and time according to the timezone

Mage::getModel('core/date')->date('Y-m-d H:i:s');
OR
date("Y-m-d H:i:s", Mage::getModel('core/date')->timestamp(time()));

Price Currency Conversion in Magento

<?php
$fromCur = 'USD'; // currency code to convert from – usually your base currency
$toCur = 'EUR'; // currency to convert to
$price = 100;
function($price, $fromCur, $toCur){
$price = Mage::helper('directory')->currencyConvert(1000, $fromCur, $toCur);
return Mage::app()->getStore()->roundPrice($price);
}

Customer login url with redirect to current page

<?php
Mage::getUrl('customer/account/login', array ( Mage_Customer_Helper_Data::REFERER_QUERY_PARAM_NAME => Mage::helper('core')->urlEncode(Mage::getUrl('*/*/*', array('_current' => true))) )); ?>');
?>

Json Encode Decode

// Json Encode and Decoding in Magento
// Json Encode an Array in Magento
$json = Mage::helper('core')->jsonEncode($array);

// Json Decode in Magento
$array = Mage::helper('core')->jsonDecode($jsonString);

Enable Template Path Hint in Magento Adminpanel Developer mode

Go to your Database and Just run this query:
INSERT INTO core_config_data (scope, scope_id, path, value)
VALUES ('default', 0, 'dev/debug/template_hints', 1),
('default', 0, 'dev/debug/template_hints_blocks', 1);

To disable them again, run this query:
UPDATE core_config_data set value = 0 where scope = 'default' and scope_id = 0 and path ='dev/debug/template_hints'
To enable again run this query:
UPDATE core_config_data set value = 1 where scope = 'default' and scope_id = 0 and path ='dev/debug/template_hints'

Setups

Attribute creation

<?php
$installer = $this;
$setup = new Mage_Eav_Model_Entity_Setup('core_setup');
$installer->startSetup();

$setup->addAttribute('customer', 'attribute_name', array(
    'label'           => 'Händlersuche erlaubt',
    'type'            => 'int',
    'input'           => 'select',
    'global'          => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_GLOBAL,
    'source'          => 'eav/entity_attribute_source_boolean',
    'default'         => 0,
    'visible'         => true,
    'required'        => false,
    'user_defined'    => true,
    'is_user_defined' => true,
    'position'        => 100,
));

Mage::getSingleton('eav/config')
    ->getAttribute('customer', 'attribute_name')
    ->setData('used_in_forms', array('adminhtml_customer'))
    ->save();
 
$installer->endSetup();
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment