Magento 1.9 Delete All Attribute Values
$attribute_code = 'YOUR_ATTRIBUTE_CODE'; // Write your attribute code here
$attribute = Mage::getModel('eav/config')->getAttribute('catalog_product', $attribute_code); // Replace catalog_product with something else if attribute belongs to different model
$options = $attribute->getSource()->getAllOptions();
$optionsDelete = array();
foreach($options as $option) {
    if ($option['value'] != "") {
        $optionsDelete['delete'][$option['value']] = true;
        $optionsDelete['value'][$option['value']] = true;
    }
}
$installer = new Mage_Eav_Model_Entity_Setup('core_setup');
$installer->addAttributeOption($optionsDelete);

 


Lukas
Lukas Stranovsky
I am the guy who made this. Sorry for typos.
Magento 1.9 – How to create attribute values programatically
$arg_attribute = 'plusstocklocation'; // Attribute code, can be color, brands, manufacturer or your custom attribute.
        $arg_value = 'Red'; // New value name

        $attr_model = Mage::getModel('catalog/resource_eav_attribute');
        $attr = $attr_model->loadByCode('catalog_product', $arg_attribute);
        $attr_id = $attr->getAttributeId();

        $option['attribute_id'] = $attr_id;
        $option['value']['any_option_name'][0] = $arg_value;

        $setup = new Mage_Eav_Model_Entity_Setup('core_setup');
        $setup->addAttributeOption($option);

 


Lukas
Lukas Stranovsky
I am the guy who made this. Sorry for typos.
Magento how to join a collection with SQL

Joining tables in Magento is relatively easy.

// Create som ecollection.
$collection = Mage::getModel('catalog/product')->getCollection();

// Join this collection with sizes.
                $collection->getSelect()->joinLeft(
                    array( 'sizes' => 'catalog_product_entity_int' ),
                    'e.entity_id = sizes.entity_id AND sizes.attribute_id = 132', // 132 is id of sizes attribute
                    array( 'size' => 'sizes.value' ));

This will produce the following SQL: SELECT `e`.*, `sizes`.`value` AS `size` FROM `catalog_product_entity` AS `e` LEFT JOIN `catalog_product_entity_int` AS `sizes` ON e.entity_id = sizes.entity_id AND sizes.attribute_id = 132 In case you want to do another type of join, there is also joinRight or joinInner


Lukas
Lukas Stranovsky
I am the guy who made this. Sorry for typos.
Magento 1.9 How to select multiple categories by ids at once

I was looking for this very long time and I had to dig for a very long time to find it, hence it is so simple.

$categoriesIDs = [125,250];
$categories = Mage::getModel('catalog/category')
              ->getCollection()
              ->addAttributeToFilter('entity_id', array('in'=>$categoriesIDs))
              ->addAttributeToSelect('name');

 


Lukas
Lukas Stranovsky
I am the guy who made this. Sorry for typos.
Magento 1.9 – Order product collection by biggest percentage discount

The other day I had to create a new filter option for products which could order them by the largest discount. I made this simple workaround where I joined product collection with table “catalog_product_entity_decimal”, which is the table containing all the prices. “attribute_id” with value 76 is special_price.
Then, I created a new column “discount” which is calculated as:

discount = (price – special_price) / (price / 100)

 

// Join the special price into the discount column.
$store = Mage::app()->getStore();
    $_productCollection->getSelect()
                       ->joinLeft(
                           array( 'sfoi' => 'catalog_product_entity_decimal' ),
                           'e.entity_id = sfoi.entity_id AND sfoi.attribute_id = 76 AND sfoi.store_id = ' . $store->getId(),
                           array( 'discount' => '((price - sfoi.value) / (price / 100))' )
                       );
// Set order to DESC
    $_productCollection->getSelect()->Order( array( new Zend_Db_Expr( 'discount DESC' ) ) );

 


Lukas
Lukas Stranovsky
I am the guy who made this. Sorry for typos.
How to create new products attribute programmatically

Attributes can be also created manually in Catalog > Attributes.
However, if your custom module requires to use new attributes, then the best practice is to create them programmatically, so when you install the module, new attributes will be created automatically without any further actions.

<?php  
$installer = new Mage_Eav_Model_Entity_Setup('core_setup');
$installer->startSetup();
$installer->addAttribute('catalog_product', 'magentoguides_attribute_key', array(
            'group'           => 'General',
            'label'           => 'Magento Guides front end label',
            'input'           => 'text',
            'type'            => 'varchar',
            'required'        => 0,
            'visible_on_front'=> 1,
            'filterable'      => 0,
            'searchable'      => 0,
            'comparable'      => 0,
            'user_defined'    => 1,
            'is_configurable' => 0,
            'global'          => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_GLOBAL,
            'note'            => '',
));
$installer->endSetup();

The new Attribute will be at the bottom of the product page by default. If you want to move it for example to prices tab. Then change ‘General’ to ‘Prices’. Or you can do it manually by navigating to Catalog > Manage attribute sets

If instead you want to use a different type than ‘text’, change ‘type’ to for example ‘textarea’.


Lukas
Lukas Stranovsky
I am the guy who made this. Sorry for typos.
How to add block on every page in admin or front

Sometimes you might want to add block or javascript everywhere to the administration or everywhere to your theme. With Magento, this is very simple. What we need to do is to create a block and then extend layout separately for admin frontend. Also, we will need 2 separate templates.

Admin

Let’s start with Admin part first. We will create a custom module Magentoguides_JavascriptEverywhere.
Module config file with the path app\code\local\Magentoguides\JavascriptEverywhere\etc\config.xml
will have the following structure:

<?xml version="1.0"?>
<config>
    <modules>
        <Magentoguides_JavascriptEverywhere>
            <version>0.1.0</version>
        </Magentoguides_JavascriptEverywhere>
    </modules>
    <frontend>
        <layout>
            <updates>
                <javascripteverywhere>
                    <file>magentoguides_javascripteverywhere.xml</file> <!-- This is the layout file for Front -->
                </javascripteverywhere>
            </updates>
        </layout>
    </frontend>
    <adminhtml>
        <layout>
            <updates>
                <module>
                    <file>magentoguides_javascripteverywhere.xml</file> <!-- This is the layout file for Admin -->
                </module>
            </updates>
        </layout>
    </adminhtml>
    <global>
        <models>
            <magentoguides_javascripteverywhere>
                <class>Magentoguides_JavascriptEverywhere_Model</class>
                <resourceModel>magentoguides_javascripteverywhere_resource</resourceModel>
            </magentoguides_javascripteverywhere>
            <magentoguides_javascripteverywhere_resource>
                <class>Magentoguides_JavascriptEverywhere_Model_Resource</class>
            </magentoguides_javascripteverywhere_resource>
        </models>
        <blocks>
            <magentoguides_javascripteverywhere>
                <class>Magentoguides_JavascriptEverywhere_Block</class>
            </magentoguides_javascripteverywhere>
        </blocks>
        <helpers>
            <magentoguides_javascripteverywhere>
                <class>Magentoguides_JavascriptEverywhere_Helper</class>
            </magentoguides_javascripteverywhere>
        </helpers>
    </global>
</config>

Next step is to define a block at  app\code\local\Magentoguides\JavascriptEverywhere\Block\Adminhtml\EverywhereBlock.php

<?php

class Magentoguides_JavascriptEverywhere_Block_Adminhtml_EverywhereBlock extends Mage_Core_Block_Template
{

}

 

Then we will create the layout file which we defined in the config.xml app\design\adminhtml\default\default\layout\magentoguides_javascripteverywhere.xml

<?xml version="1.0"?>
<layout version="0.1.0">
    <default>
        <reference name="content">
            <block type="magentoguides_javascripteverywhere/adminhtml_everywhereBlock" name="securitycheck" template="magentoguides_javascripteverywhere/jseverywhere.phtml"/>
        </reference>
    </default>
</layout>

And lastly the template file app\design\adminhtml\default\default\template\magentoguides_javascripteverywhere\jseverywhere.phtml

<b>This html code will be shown everywhere!</b>
<script>
    alert('This javascript will be executed everywhere!');
</script>

 

Front

For the Front, we have to create same layout update file and same template file, however, in different directory since files for front and admin are separated.

Layout update file app\design\frontend\base\default\layout\magentoguides_javascripteverywhere.xml

<?xml version="1.0"?>
<layout version="0.1.0">
    <default>
        <reference name="content">
            <block type="magentoguides_javascripteverywhere/adminhtml_everywhereBlock" name="securitycheck" template="magentoguides/javascripteverywhere/myfile.phtml"/>
        </reference>
    </default>
</layout>

Template file with same content as the one we created above app\design\frontend\base\default\template\magentoguides\javascripteverywhere\myfile.phtml

<b>This html code will be shown everywhere!</b>
<script>
    alert('This javascript will be executed everywhere!');
</script>

 

Download module


Lukas
Lukas Stranovsky
I am the guy who made this. Sorry for typos.
How To Export Products in Magento 1 From Terminal Via SSH

Prerequisites

You will need SSH access to your Magento website.

 

First you will need to find id of your data profile. Go to your Magento backend and:

System > Import/Export > Dataflow – Profiles

By default, for exporting products it should be id 1.

Create a file custom_product_export.php in the root of your magento app with following code:

 

<?php


set_time_limit(0);
// THIS SCRIPT JUST INITIALS THE PROFILE TO BE RUN VIA MAGENTO ADMIN "RUN PROFILE IN POPUP". Its the same thing as click just via this file that you can run via cron
$profileId = 1; // ID of your data profile

require_once 'app/Mage.php';
umask(0);
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);

$profile = Mage::getModel('dataflow/profile');
$userModel = Mage::getModel('admin/user');
$userModel->setUserId(0);
Mage::getSingleton('admin/session')->setUser($userModel);
$profile->load($profileId);
if (!$profile->getId()) {
    Mage::getSingleton('adminhtml/session')->addError('ERROR: Incorrect profile id');
}

Mage::register('current_convert_profile', $profile);
$profile->run();
$recordCount = 0;
$batchModel = Mage::getSingleton('dataflow/batch');
echo "EXPORT COMPLETE. BATCHID: " . $batchModel->getId();

now run the script with

php custom_product_export.php

 

If you will get error Allowed memory size exhausted, try run it like this

php -dmemory_limit=50G custom_product_export.php

Your Exported .csv file will be saved in magento root var/export/ folder.


Lukas
Lukas Stranovsky
I am the guy who made this. Sorry for typos.
How To Add System Configuration Fields

We are going to add new configuration input.

Creating new system configuration inputs is very convenient in magento, since there is no need to do anything with database.

Create system.xml in your module etc/ directory.

<config>
    <sections>
        <general translate="label">
            <groups>
                <example>
                    <label>Example options</label>
                    <sort_order>0</sort_order>
                    <show_in_default>1</show_in_default>
                    <show_in_website>1</show_in_website>
                    <show_in_store>1</show_in_store>
                    <fields>
                        <some_field translate="label">
                            <label>Some Field</label>
                            <frontend_type>text</frontend_type>
                            <show_in_default>1</show_in_default>
                            <show_in_website>1</show_in_website>
                            <show_in_store>1</show_in_store>
                        </some_field>
                    </fields>
                </example>
            </groups>
        </general>
    </sections>
</config>

Usage

You can get the value of your configuration field by calling this function in code.

Mage:getStoreConfig('general/example/some_field');
//general - this is section
//example - this is group
// some_field - this is field
/*Follow the system.xml to know where they come from*/

 


Lukas
Lukas Stranovsky
I am the guy who made this. Sorry for typos.
Create New Admin User From SQL
SET @SALT = "rp";
SET @PASS = CONCAT(MD5(CONCAT( @SALT , "password") ), CONCAT(":", @SALT ));
SELECT @EXTRA := MAX(extra) FROM admin_user WHERE extra IS NOT NULL;
 
INSERT INTO `admin_user` (firstname,lastname,email,username,password,created,lognum,reload_acl_flag,is_active,extra,rp_token_created_at) 
VALUES ('Firstname','Lastname','email@example.com','myuser',@PASS,NOW(),0,0,1,@EXTRA,NOW());
 
INSERT INTO `admin_role` (parent_id,tree_level,sort_order,role_type,user_id,role_name) 
VALUES (1,2,0,'U',(SELECT user_id FROM admin_user WHERE username = 'myuser'),'Firstname');

Credit: activo


Lukas
Lukas Stranovsky
I am the guy who made this. Sorry for typos.