Magento Snippets
Find attribute_id
SELECT * FROM eav_attribute where attribute_code = 'is_anchor'
Update all of them with anchor_id from above (usually is ID 51)
UPDATE `catalog_category_entity_int` set value = 1 where attribute_id = 51
Create an catalog product "video" attribute and supply Youtube ID's to the field.
<?php if($_product->getVideo()): ?>
<div class="video-link"><a href="#" onclick="openLight('<?php echo $_product->getVideo(); ?>');"><?php echo $this->__('Watch Video'); ?></a></div>
<?php endif; ?>
<script type="text/javascript">
//<![CDATA[
function openLight(zoom_video){
$$('body > .wrapper')[0].insert("<div id='overlay'></div>");
$('overlay').setStyle({'height':document.body.clientHeight+'px'});
new Effect.Opacity('overlay',{from:0.0,to:0.8,duration:0.3,transition:Effect.Transitions.sinoidal,afterFinish:function(){
$$('body > .wrapper')[0].insert("<div id='lightbox'><iframe width='560' height='315' src='http://www.youtube.com/embed/"+zoom_video+"' frameborder='0' allowfullscreen></iframe></div>");
$$('#lightbox')[0].insert("<a>close</a>");
$$('#lightbox > a')[0].observe('click',function(){
$('overlay').remove();
$('lightbox').remove();
});
}});
}
//]]>
</script>
find . -type f -exec grep -qF 'Varien_Profiler' {} \; -exec sed -i '/Varien_Profiler/d' {} \;
UPDATE catalog_product_entity_media_gallery AS mg,
catalog_product_entity_media_gallery_value AS mgv,
catalog_product_entity_varchar AS ev
SET ev.value = mg.value
WHERE mg.value_id = mgv.value_id
AND mg.entity_id = ev.entity_id
AND ev.attribute_id IN (85, 86, 87) #<-- Find them in catalog_product_entity_varchar
AND mgv.position = 1;
grep -r Mage::dispatchEvent /path/to/your/Magento/* > events.txt
See for more in-depth details: http://magento.stackexchange.com/questions/153/where-can-i-find-a-complete-list-of-magento-events/167#comment3986_167
grep -shR "\->__('" *|sed "s/\(;|?>\)/\1\n/g;s/^[ \t]*//;s/[ \t]*$//;s/.*->__('\([^']\+\)'[^)]*).*/\1/g"
Example: (with tables to ignore from Magento minus usual stuff like -u -p etc.)
mysqldump --ignore-table=db.log_customer -–ignore-table=db.log_quote -–ignore=db.log_summary –-ignore=db.log_summary_type –-ignore=db.log_url -–ignore=db.log_url_info -–ignore=db.log_visitor -–ignore=db.log_visitor_info --ignore=db.log_visitor_online –-ignore=db.log_summary –-ignore=db.enterprise_logging_event –-ignore=db.enterprise_logging_event_changes
Notes:
Pear for 1.4, mage for 1.5. File downloaded into /downloader/.cache/community/
./pear download magento-community/Shipping_Agent
./mage download community Shipping_Agent
If for some reason you need to download a Magento Connect extension archive from command line, use the following :
wget http://connect.magentocommerce.com/TYPE/get/EXTENSION_NAME-X.X.X.tgz
TYPE must be replaced with real extension type(usually core or community), EXTENSION_NAME with real(machine readable) extension name and X.X.X must be replaced with the real version number. To retrieve real TYPE and the real machine readable EXTENSION_NAME simply look at it’s extension key and take into a count it’s format magento-TYPE/EXTENSION_NAME.
For example:
http://www.magentocommerce.com/extension/518/blank-theme
Extension key: magento-core/Interface_Frontend_Default_Blank Version(at the time of writing): 1.4.1.1 Download URL:
wget http://connect.magentocommerce.com/core/get/Interface_Frontend_Default_Blank-1.4.1.1.tgz
Other example:
http://www.magentocommerce.com/extension/974/yoast-blank-seo-theme
Extension key: magento-community/Yoast_Blank_Seo_Theme Version(at the time of writing): 1.4.1 Download URL:
wget http://connect.magentocommerce.com/community/get/Yoast_Blank_Seo_Theme-1.4.1.tgz
<?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
*/
?>
<?php
$_category = Mage::getModel('catalog/category')->load(89);
$_category_url = $_category->getUrl();
?>
<?php
$_product_1 = Mage::getModel('catalog/product')->load(12);
$_product_2 = Mage::getModel('catalog/product')->loadByAttribute('sku','cordoba-classic-6-String-guitar');
?>
<?php
// input is $_product and result is iterating child products
$childProducts = Mage::getModel('catalog/product_type_configurable')->getUsedProducts(null, $product);
?>
<?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());
}
?>
<?php Mage::log('Your Log Message', Zend_Log::INFO, 'your_log_file.log'); ?>
<?php echo $this->getLayout()->createBlock('cms/block')->setBlockId('block-name')->toHtml(); ?>
First approach: page.xml - you can add something like
<action method="addJs"><script>path/to/my/file.js</script></action>
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 echo $this->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
<!-- existing line --> <block type="page/html_head" name="head" as="head">
<!-- new sub-block you're adding --> <block type="core/template" name="mytemplate" as="mytemplate" template="page/mytemplate.phtml"/>
...
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).
<?php $logged_in = Mage::getSingleton('customer/session')->isLoggedIn(); // (boolean) ?>
<?php
$currentCategory = Mage::registry('current_category');
$currentProduct = Mage::registry('current_product');
$currentCmsPage = Mage::registry('cms_page');
?>
<?php
require_once('app/Mage.php'); //Path to Magento
umask(0);
Mage::app();
// Run you code here
?>
<?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);
?>
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.
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';
<?php
// http://example.com/
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);
?>
<?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();
?>
<?php echo Mage::helper('core/url')->getCurrentUrl(); ?>
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.
<div id="leftnav">
<?php $helper = $this->helper('catalog/category') ?>
<?php $categories = $this->getStoreCategories() ?>
<?php if (count($categories) > 0): ?>
<ul id="leftnav-tree" class="level0">
<?php foreach($categories as $category): ?>
<li class="level0<?php if ($this->isCategoryActive($category)): ?> active<?php endif; ?>">
<a href="<?php echo $helper->getCategoryUrl($category) ?>"><span><?php echo $this->escapeHtml($category->getName()) ?></span></a>
<?php if ($this->isCategoryActive($category)): ?>
<?php $subcategories = $category->getChildren() ?>
<?php if (count($subcategories) > 0): ?>
<ul id="leftnav-tree-<?php echo $category->getId() ?>" class="level1">
<?php foreach($subcategories as $subcategory): ?>
<li class="level1<?php if ($this->isCategoryActive($subcategory)): ?> active<?php endif; ?>">
<a href="<?php echo $helper->getCategoryUrl($subcategory) ?>"><?php echo $this->escapeHtml(trim($subcategory->getName(), '- ')) ?></a>
</li>
<?php endforeach; ?>
</ul>
<script type="text/javascript">decorateList('leftnav-tree-<?php echo $category->getId() ?>', 'recursive')</script>
<?php endif; ?>
<?php endif; ?>
</li>
<?php endforeach; ?>
</ul>
<script type="text/javascript">decorateList('leftnav-tree', 'recursive')</script>
<?php endif; ?>
</div>
<?php echo Zend_Debug::dump($thing_to_debug, 'debug'); ?>
<?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']);
?>
First, use get_class
to get the name of an object's class.
<?php $class_name = get_class($object); ?>
Then, pass that get_class_methods
to get a list of all the callable methods on an object
<?php
$class_name = get_class($object);
$methods = get_class_methods($class_name);
foreach($methods as $method)
{
var_dump($method);
}
?>
<?php if($_product->isSaleable()) { // do stuff } ?>
<?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;
}
?>
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;
In /app/design/frontend/default/site/template/catalog/product/view/type/
<?php $_helper = $this->helper('catalog/output'); ?>
<?php $_associatedProducts = $this->getAllowProducts() ?>
<?php //var_dump($_associatedProducts); ?>
<br />
<br />
<?php if (count($_associatedProducts)): ?>
<?php foreach ($_associatedProducts as $_item): ?>
<a href="<?php echo $_item->getProductUrl() ?>"><?php echo $_helper->productAttribute($_item, $_item->getName(), 'name') ?> | <?php echo $_item->getName() ?> | <?php echo $_item->getPrice() ?></a>
<br />
<br />
<?php endforeach; ?>
<?php endif; ?>
<?php
$countryList = Mage::getResourceModel('directory/country_collection')
->loadData()
->toOptionArray(false);
echo '<pre>';
print_r( $countryList);
exit('</pre>');
?>
<?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; ?>
<?php
$fieldset->addField('country', 'select', array(
'name' => 'country',
'label' => 'Country',
'values' => Mage::getModel('adminhtml/system_config_source_country')->toOptionArray(),
));
?>
<?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;
?>
<?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());
}
?>
<?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
}
?>
UPDATE
`core_config_data`
SET
`value` = 0
WHERE
`path` = "dev/debug/template_hints"
OR
`path` = "dev/debug/template_hints_blocks";
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`;
<?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)
?>
//Full path to the log file:
$logPath = Mage::getConfig()->getOptions()->getVarDir().DS.$file_name.time().'.xml';
//Layout model: Mage_Core_Model_Layout
$layout = Mage::getSingleton('core/layout');
//Generate our xml with Mage_Core_Layout_Update model and save it in a file
$xml = '<'.'?xml version="1.0"?'.'>';
$xml .= '<layout>'.trim($layout->getUpdate()->asString()).'</layout>';
file_put_contents($logPath, $xml);
<config>
<stores>
<default>
<web>
<unsecure>
<base_url><![CDATA[http://default-magento-store.com]]></base_url>
</unsecure>
<secure>
<base_url><![CDATA[http://default-magento-store.com]]></base_url>
</secure>
</web>
</default>
<admin>
<web>
<unsecure>
<base_url><![CDATA[http://default-magento-store.com]]></base_url>
</unsecure>
<secure>
<base_url><![CDATA[http://default-magento-store.com]]></base_url>
</secure>
</web>
</admin>
</stores>
<websites>
<base>
<web>
<unsecure>
<base_url><![CDATA[http://default-magento-store.com]]></base_url>
</unsecure>
<secure>
<base_url><![CDATA[http://default-magento-store.com]]></base_url>
</secure>
</web>
</base>
<admin>
<web>
<unsecure>
<base_url><![CDATA[http://default-magento-store.com]]></base_url>
</unsecure>
<secure>
<base_url><![CDATA[http://default-magento-store.com]]></base_url>
</secure>
</web>
</admin>
</websites>
<default>
<web>
<unsecure>
<base_url><![CDATA[http://default-magento-store.com]]></base_url>
</unsecure>
<secure>
<base_url><![CDATA[http://default-magento-store.com]]></base_url>
</secure>
</web>
</default>
<!-- ... Rest of your local.xml -->
</config>
<default>
<reference name="content">
<block type="core/text" name="fix.console" as="fix.console">
<action method="setText">
<text><![CDATA[<script type="text/javascript">
iframe = document.createElement('iframe');
iframe.style.display = 'none';
document.getElementsByTagName('body')[0].appendChild(iframe);
window.console = iframe.contentWindow.console;
console.firebug = "faketrue";
</script>]]></text>
</action>
</block>
</reference>
</default>
<disable_local_modules>true</disable_local_modules>
// Save
$cache->save(date("r"), "nick_date", array("nicks_cache"), 10);
$cache->save("hello world - " . time(), "nick_helloworld", array("nicks_cache"), 60*60);
// Load
$cache->load("nick_date");
// Remove
$cache->remove("nick_date");
// Flush group
$cache->flush("nicks_cache");
/* There are few 'notification types' in Magento you can utilize: */
// error:
Mage::getSingleton('core/session')->addError('Custom error here');
// warning:
Mage::getSingleton('core/session')->addWarning('Custom warning here');
// notice:
Mage::getSingleton('core/session')->addNotice('Custom notice here');
// success:
Mage::getSingleton('core/session')->addSuccess('Custom success here');
$routeName = Mage::app()->getRequest()->getRouteName();
$identifier = Mage::getSingleton('cms/page')->getIdentifier();
if($routeName == 'cms' && $identifier == 'home') {
echo 'You are in Homepage!';
} else {
echo 'You are NOT in Homepage!';
}
SET FOREIGN_KEY_CHECKS=0;
-- reset 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;
SET FOREIGN_KEY_CHECKS=1;
<?php
require_once 'app/Mage.php';
Mage::app();
$quote = Mage::getModel('sales/quote')
->setStoreId(Mage::app()->getStore('default')->getId());
if ('do customer orders') {
// for customer orders:
$customer = Mage::getModel('customer/customer')
->setWebsiteId(1)
->loadByEmail('customer@example.com');
$quote->assignCustomer($customer);
} else {
// for guesr orders only:
$quote->setCustomerEmail('customer@example.com');
}
// add product(s)
$product = Mage::getModel('catalog/product')->load(8);
$buyInfo = array(
'qty' => 1,
// custom option id => value id
// or
// configurable attribute id => value id
);
$quote->addProduct($product, new Varien_Object($buyInfo));
$addressData = array(
'firstname' => 'Test',
'lastname' => 'Test',
'street' => 'Sample Street 10',
'city' => 'Somewhere',
'postcode' => '123456',
'telephone' => '123456',
'country_id' => 'US',
'region_id' => 12, // id from directory_country_region table
);
$billingAddress = $quote->getBillingAddress()->addData($addressData);
$shippingAddress = $quote->getShippingAddress()->addData($addressData);
$shippingAddress->setCollectShippingRates(true)->collectShippingRates()
->setShippingMethod('flatrate_flatrate')
->setPaymentMethod('checkmo');
$quote->getPayment()->importData(array('method' => 'checkmo'));
$quote->collectTotals()->save();
$service = Mage::getModel('sales/service_quote', $quote);
$service->submitAll();
$order = $service->getOrder();
printf("Created order %s\n", $order->getIncrementId());
private function _attachProductToConfigurable( $_childProduct, $_configurableProduct ) {
$loader = Mage::getResourceModel( 'catalog/product_type_configurable' )->load( $_configurableProduct );
$ids = $_configurableProduct->getTypeInstance()->getUsedProductIds();
$newids = array();
foreach ( $ids as $id ) {
$newids[$id] = 1;
}
$newids[$_childProduct->getId()] = 1;
$loader->saveProducts( $_configurableProduct->getId(), array_keys( $newids ) );
}