Search This Blog

Tuesday 29 January 2013

Auto Pre-pend a file when any file is accessed from the folder

Usually it helps to authenticate the user for the static website in a sub folder. You can include the check.php file on the server and write logic for authentication.

php_value auto_prepend_file "DOCUMENT_ROOT/check.php"

Display Country warehouse flag using Multi warehouse extension

Script to display contry flags for the available warehouses using Multi warehouse extension.


$countryStocks = array(); $productId = array(9736, 9737, 9738);
$collection = Mage::getModel('warehouse/warehouse')->getCollection();
if($collection->count() > 0)
{
    $innoStockObj = new Innoexts_Warehouse_Model_Cataloginventory_Stock_Item_Api();
    foreach($collection as $warehouse)
    {
        if($warehouse->getId())
        {
            $stockId = $warehouse->getStockId();
            $countryId = strtolower($warehouse->getOriginCountryId());
            $result = $innoStockObj->itemsByStock($productId, $stockId);
            foreach($result as $resultRow)
            {
                if(isset($resultRow['qty']) and $resultRow['qty'] > 0 and isset($resultRow['is_in_stock']) and $resultRow['is_in_stock'] == 1)
                {
                    $countryStocks[$resultRow['product_id']][$countryId]['description'] = '';
                    if(isset($countryStocks[$countryId]))
                        $countryStocks[$resultRow['product_id']][$countryId] = array('qty' => $countryStocks[$countryId]['qty'] + $resultRow['qty'], 'description' => $warehouse->getDescription());
                    else
                        $countryStocks[$resultRow['product_id']][$countryId] = array('qty' => $resultRow['qty'], 'description' => $warehouse->getDescription());
                    $filename = Mage::getBaseDir('media').DS.'flags'.DS.$countryId.".png";
                    if(file_exists($filename))
                    {
                        $countryStocks[$resultRow['product_id']][$countryId]['countryFlag'] = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA).'flags/'.$countryId.".png";
                    }
                }
            }
        }   
    }
}
//print_r($countryStocks);
?>
<?php $productId = 9736; ?>
<?php if(count($countryStocks) > 0 and count($countryStocks[$productId]) > 0): ?>
<?php foreach($countryStocks[$productId] as $countryStock): ?>
    <?php if(isset($countryStock['countryFlag'])): ?>
        <img src="<?php echo $countryStock['countryFlag']; ?>" title="<?php echo $countryStock['description']; ?>" alt="<?php echo $countryStock['description']; ?>" />
    <?php endif; ?>
<?php endforeach; ?>
<?php endif; ?>

Make sure to place country flag images in /media/flags folder with naming country code.png

Monday 28 January 2013

Get and Set Config data

$lastUpdatedDate = Mage::getStoreConfig('test/newarrivals/updateddate');

Mage::getModel('core/config')->saveConfig('test/newarrivals/updateddate', $lastUpdatedDate );

Wednesday 23 January 2013

Log all SQL queries in Magento

In Varien_Db_Adapter_Pdo_Mysql

Magento : lib/varien/Db/Adapter/Pdo/Mysql.php
set
protected $_debug               = true;
protected $_logAllQueries       = true;
 
and (if nor already there) create the folder defined in

protected $_debugFile           = 'var/debug/sql.txt';
 
Give read / write permission

Script to Unzip the GZipped file in PHP

function uncompress($srcName, $dstName) {
    $sfp = gzopen($srcName, "rb");
    $fp = fopen($dstName, "w");

    while ($string = gzread($sfp, 4096)) {
        fwrite($fp, $string, strlen($string));
    }
    gzclose($sfp);
    fclose($fp);
}
uncompress($srcName, $dstName);

Include a block from a module in any PHTML file

<?php 
echo $this->getLayout()->createBlock('newmodule/newblock')
->setTemplate('newmodule/newblock.phtml')->toHtml();
?>

Tuesday 22 January 2013

Save customer address programatically

                ### Save Address Info for the Customer ###
                $customerData = $this->getRequest()->getPost();
                $address = Mage::getModel("customer/address");
                if($customer->getDefaultBilling())
                {
                    $address->load($customer->getDefaultBilling()); // Updating the default billing address if customer already have
                }
                $address->setCustomerId($customer->getId());
                $address->setData($customerData);
                $address->setIsDefaultBilling($this->getRequest()->getParam('default_billing', false)); // Make it as default billing address
                $address->setIsDefaultShipping($this->getRequest()->getParam('default_shipping', false)); // Make it as default shipping address
                $address->save();
                $customer->default_billing = $address->getId();  // Make it as default billing address
                $customer->default_shipping = $address->getId(); // Make it as default shipping address
                $customer->save();
                ### Save Address Info for the Customer ###

Friday 18 January 2013

Redirect to My Downloads page in checkout success

Script to redirect (after 10 seconds) the customer to my downloads page if the order contains downloadable item. Please the following code in success.phtml page at the end in your current theme.

<?php
    $hasDownloadableItem = false;
    try {
        if ($this->getOrderId())
        {
            $orderId = $this->getOrderId();
            $order = Mage::getModel('sales/order')->loadByIncrementId($orderId);
            $items = $order->getAllItems();
            foreach ($items as $itemId => $item)
            {
                //$_product = Mage::getModel('catalog/product')->load($item->getProductId());
                $itemData = $item->getData();
                if(isset($itemData['product_type']) and $itemData['product_type']=="downloadable")
                {
                    $hasDownloadableItem = true;
                    break;
                }
            }
        }
    } catch (Exception $e) {
        Mage::log($e->getMessage(), 7);
    }
?>
<?php if($hasDownloadableItem): ?>
<script type="text/javascript">
//<![CDATA[
    setTimeout(function(){ location.href = '<?php echo $this->getUrl() ?>downloadable/customer/products/'},10000);
//]]>
</script>
<?php endif;?>

Note: This is for the logged in customers only.

Thursday 17 January 2013

Session start in Wordpress

To initiate sessions in Wordpress , Place the following code in theme functions.php file.

function init_sessions() {
    if (!session_id()) {
        session_start();
    }
}
add_action('init', 'init_sessions');



Of-course you can place the same code in root index.php, wp-config.php files but upgrading the WP to new version will override the changes you made to core files.

Wednesday 16 January 2013

Capture invoice offline programatically

 Script to Capture invoice offline, this will change the invoice status from pending to paid and update the paid totals related to the invoice in the database.

   require_once 'app/Mage.php';
    $path = Mage::app()->getConfig()->getTempVarDir(); // This line is just to initiate the Magento APP

    try {
        $orderId = '100000066';
        $invoiceId = '100000006';
        $order  = Mage::getModel('sales/order')->loadByIncrementId($orderId);
        //print_r( $order->getData());     exit;
        if (!$order->canCreditmemo()) {
            if ($invoiceId) {
                $invoice = Mage::getModel('sales/order_invoice')
                    ->loadByIncrementId($invoiceId)
                    ->setOrder($order);
                //print_r( $invoice->getData());     exit;
                $capture_case = 'offline';
                //$invoice->setRequestedCaptureCase($capture_case)->capture()->save();
                $invoice->setRequestedCaptureCase($capture_case)->setCanVoidFlag(false)->pay();//->save();

                $transactionSave = Mage::getModel('core/resource_transaction')
                    ->addObject($invoice)
                    ->addObject($invoice->getOrder());
                $transactionSave->save();
            }
        }
    } catch (Exception $e) {
        echo $e->getMessage();
    }


Monday 14 January 2013

CSS Font-Size: em vs. px vs. pt vs. percent

Meet the Units

  1. “Ems” (em): The “em” is a scalable unit that is used in web document media. An em is equal to the current font-size, for instance, if the font-size of the document is 12pt, 1em is equal to 12pt. Ems are scalable in nature, so 2em would equal 24pt, .5em would equal 6pt, etc. Ems are becoming increasingly popular in web documents due to scalability and their mobile-device-friendly nature.
  2. Pixels (px): Pixels are fixed-size units that are used in screen media (i.e. to be read on the computer screen). One pixel is equal to one dot on the computer screen (the smallest division of your screen’s resolution). Many web designers use pixel units in web documents in order to produce a pixel-perfect representation of their site as it is rendered in the browser. One problem with the pixel unit is that it does not scale upward for visually-impaired readers or downward to fit mobile devices.
  3. Points (pt): Points are traditionally used in print media (anything that is to be printed on paper, etc.). One point is equal to 1/72 of an inch. Points are much like pixels, in that they are fixed-size units and cannot scale in size.
  4. Percent (%): The percent unit is much like the “em” unit, save for a few fundamental differences. First and foremost, the current font-size is equal to 100% (i.e. 12pt = 100%). While using the percent unit, your text remains fully scalable for mobile devices and for accessibility.
Click here for more information.

Wednesday 9 January 2013

Add rel=next and rel=prev for all the paginated pages

Use the following code in your theme functions.php

    function rel_next_prev(){
        global $paged;
        if ( get_previous_posts_link() ) { ?>
<link rel="prev" href="<?php echo get_pagenum_link( $paged - 1 ); ?>" /><?php
        }
        if ( get_next_posts_link() ) { ?>

<link rel="next" href="<?php echo get_pagenum_link( $paged +1 ); ?>" /><?php
        }
    }
    add_action("wp_head", "rel_next_prev");

Get the post / page ID in functions.php

Usually the global variable $post will give the user all the information of the current post / page. This global variable is not available in functions.php (if the code is not in a function) so you can use the following code snippet to get the ID of the post/page ID based on current URL.

$currenturl = explode('?', 'http://'.$_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"]);
$curpostId = url_to_postid($currenturl [0]);




$curpostId value will be zero if the current page is not a post / page.

Sunday 6 January 2013

Cron Job in Magento

A few features in Magento require a script to be run periodically.  These features include, but are not limited to:


1. Catalog Price rules
2. Sending Newsletters
3. Generating Google Maps
4. Customer Alerts/Notifications (product price change, product back to stock)

Saturday 5 January 2013

Save Core Config data prgramatically

$coreConfig = new Mage_Core_Model_Config();
$coreConfig ->saveConfig($path, $value, $scope = 'default', $scopeId = 0);
Mage::app()->getConfig()->reinit();
Mage::app()->reinitStores();