Magento get category products

<?php
// Method 1
$category_id = 10; // if you know static category ID then enter number

$_category = Mage::getModel('catalog/category')->load($category_id);

$collection = $_category
			->getProductCollection()
			->addAttributeToSelect('*')
			->addAttributeToFilter('status', 1) // Filter product status is enabled
			->addAttributeToFilter('visibility', 4) // Filter product visibility is Catalog, Search
			->addStoreFilter()
			->setOrder('price', 'ASC')
			->setPageSize(4) // Limit to get 4 products
			->load();
			
foreach ($collection as $product) {
	echo $product->getId() . '<br />';
    echo $product->getName() . '<br />';
    echo (float) $product->getPrice() . '<br />';
    echo $product->getDescription() . '<br />';
    echo $product->getShortDescription() . '<br />';
    echo $product->getTypeId() . '<br />';
    echo $product->getStatus() . '<br />';
    echo $product->getSpecialPrice() . '<br />';
    echo $product->getProductUrl();
}

// Method 2
$category_id = 43; // if you know static category ID then enter number

$_category = Mage::getModel('catalog/category')->load($category_id);
			
$collection = Mage::getModel('catalog/product')
			->getCollection()
			->addCategoryFilter($_category)
			->addAttributeToSelect('*')
			->addAttributeToFilter('status', 1) // Filter product status is enabled
			->addAttributeToFilter('visibility', 4) // Filter product visibility is Catalog, Search
			->addStoreFilter()
			->setOrder('price', 'ASC')
			->setPageSize(4) // Limit to get 4 products
			->load();
			
foreach ($collection as $product) {
	echo $_category->getName() . '<br />';
	echo $product->getId() . '<br />';
    echo $product->getName() . '<br />';
    echo (float) $product->getPrice() . '<br />';
    echo $product->getDescription() . '<br />';
    echo $product->getShortDescription() . '<br />';
    echo $product->getTypeId() . '<br />';
    echo $product->getStatus() . '<br />';
    echo $product->getSpecialPrice() . '<br />';
    echo $product->getProductUrl();
}

Magento get order items

// get order items
// assume you know order id or order increment id

<?php

// order id, $orderId
$_order = Mage::getModel('sales/order')->load($orderId);

// order increment id, $orderIncrementId
$_order = Mage::getModel('sales/order')->loadByIncrementId($orderIncrementId);

$_items = $_order->getAllItems();
foreach ($_items as $item)
{
	echo $item->getName() . ' ';
	echo $item->getPrice() . ' ';   
	echo $item->getSku() . ' ';
	echo $item->getProductId() . ' ';
	echo $item->getQtyToInvoice() . '<br />';
}

?>

Enjoy Magento! Hope that’s useful for you. Any question and error of my code please let me know by a comment.

Magento get last order id

// get last order id
// in order success page, app/design/frontend/[your_package]/[your_theme]/template/checkout/success.phtml, that's very simple
<?php echo $this->getOrderId(); ?>

// in any .phmtl & .php files
<?php

$orders = Mage::getModel('sales/order')->getCollection()
     ->setOrder('entity_id','DESC')
     ->setPageSize(1)
     ->setCurPage(1);
$orderId = $orders->getFirstItem()->getEntityId();
echo $orderId;

?>

Enjoy Magento! Hope that’s useful for you. Any question and error of my code please let me know by a comment.

Magento get base url

// get base url in template files, *.phtml

<?php echo $this->getBaseUrl(); ?>
or
<?php echo Mage::getBaseUrl(); ?>

Run Magento code outside of Magento

Sometimes, running update scripts to quickly update the database or to export some data does not require a complete module to hold the code. For these types of operations you can build a shell script to get into Magento’s environment without executing a traditional browser based request. The file is basically the Magento index.php file with one major change, instead of Mage::run(’default’)we will simply use Mage::app(’default’). This type of file can be used to export pending orders, update product categorization, change available quantities, or any other type of automated maintenance.

<?php

require_once 'app/Mage.php';
umask(0);
Mage::app('default');

//add your own code below:
//load a category
$categoryId = 1;
$_category = Mage::getModel('catalog/category')->load($categoryId);

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

?>

Magento get skin url

// get skin url in template files, *.phtml

// unsecure skin url
<?php echo $this->getSkinUrl(); ?>

<?php echo $this->getSkinUrl('images/logo.gif'); ?>

or
<?php echo Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_SKIN); ?>

// secure skin url
<?php echo $this->getSkinUrl('images/logo.gif', array('_secure' => true)); ?>

//get skin url in CMS pages or static blocks

{{skin url='images/logo.gif'}}

e.g.: <img src="{{skin url='images/logo.gif'}}" title="" alt="" />

 

Install and upgrade your custom module in Magento

Magento automatically installs or upgrades any module that it encounters during runtime. The installation files are located under YourModule/sql/yourmodule_setup/mysql4-install-X.Y.Z.php. The trigger for running this file is that your module’s version number is not present in the DB table `core_resource` and that you have defined a version number in your module’s etc/config.xml file. You will also need to define a global resource for your module’s setup, use a tag name of <yourmodule_setup>. Without the resource definition that includes both setup module and a connection, the installation or upgrade will not perform, even if you increase the version number.

etc/config.xml

<?xml version="1.0"?>
<config>
	<modules>
		<Company_YourModule>
			<version>1.1.0</version>
		</Company_YourModule>
	</modules>
	<global>
		<resources>
			<yourmodule_setup>
				<setup>
					<module>Company_YourModule</module>
				</setup>
				<connection>
					<use>core_setup</use>
				</connection>
			</yourmodule_setup>
		</resources>
	</global>
</config>

Given that XML file, and an absence of any record containing company_yourmodule in table `core_resource`, your module’s install file will be run the next time that module is executed. Once installed, upgrades can be triggered when you change the version number in the XML configuration file to be greater than the value in table `core_resource`. This will trigger a succession of any YourModule/sql/yourmodule_setup/mysql4-upgrade-X.Y.Z.php file that has a version number greater than the number found in the `core_resource` table.

Install module file sample: mysql4-install-1.0.0.php

<?php

$installer = $this;

$installer->startSetup();

$installer->run("INSERT INTO {$this->getTable('core_config_data')} (`path`, `value`) VALUES ('onestepcheckout/general/geoip_database', 'GeoIp/GeoLiteCity.dat')");

$installer->endSetup();

?>

Upgrade module file sample: mysql4-upgrade-1.0.0-1.1.0.php

<?php

$installer = $this;
$installer->startSetup();

$resource = Mage::getResourceModel('sales/order_collection');
if(!method_exists($resource, 'getEntity')){

    $table = $this->getTable('sales_flat_order');
    $query = 'ALTER TABLE `' . $table . '` ADD COLUMN `onestepcheckout_customercomment` TEXT CHARACTER SET utf8 DEFAULT NULL';
    $connection = Mage::getSingleton('core/resource')->getConnection('core_write');
    try {
        $connection->query($query);
    } catch (Exception $e) {

    }
}

$installer->endSetup();
?>

Magento get js url, get current url, get home url

// get js url in template files, *.phtml

<?php echo Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_JS); ?>

// get current url in template files, *.phtml

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

// get home url in template files, *.phtml

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

 

Magento get media url

// get media url in template files, *.phtml

<?php echo Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA); ?>

// get media url in CMS pages or static blocks

{{media url='images/banner.png'}}

e.g.: <img src="{{media url='images/banner.png'}}" title="" alt="" />

 

Magento delete orders

Magento by default does not allow you to delete orders. While this decision makes good sense, many users are still in need of this functionality to delete test orders. Deleting a order isn’t a simple task. Because you have to remove invoices, creditnotes and shipments firstly that related to order you want to delete. I coded a scirpt for that task. Hope useful!

<?php
// comment the following two lines before execute shis script
echo 'No access permission';
exit;

$mageFilename = '../app/Mage.php';
require_once $mageFilename;
Varien_Profiler::enable();
Mage::setIsDeveloperMode(true);
ini_set('display_errors', 1);
umask(0);
Mage::app('default');
Mage::register('isSecureArea', 1);

// order increment ID you want to delete. Delete one Order to execute this order once.
$incrementId = 100000037;
 
$order = Mage::getModel('sales/order')->loadByIncrementId($incrementId);
$invoices = $order->getInvoiceCollection();
foreach ($invoices as $invoice){
$invoice->delete();
}
$creditnotes = $order->getCreditmemosCollection();
foreach ($creditnotes as $creditnote){
$creditnote->delete();
}
$shipments = $order->getShipmentsCollection();
foreach ($shipments as $shipment){
$shipment->delete();
}
if ($order->delete()) {
	echo 'the Order of order # ' . $incrementId . ' has been deleted from database.';
} else {
	echo 'Deletion failed.';
}

?>

Older posts «