Create Global Function In Magento

Posted: June 9th, 2011 | Author: | Filed under: magento, web | Tags: | 6 Comments »

This code will allow you to add a function that can be called from anywhere within Magento. It extends the helper class

1) Create a file named ‘Mycode.xml’ and copy it to app/etc/modules/ – it should look like this:

<?xml version="1.0"?>
<config>
    <modules>
		<Mycode_Function>
			<active>true</active>
			<codePool>local</codePool>
		</Mycode_Function>
    </modules>
</config>

2) Create the directory
app/code/local/Mycode/Function/etc
and then create a file named ‘config.xml’
In it copy:

<?xml version="1.0"?>
<config>
 
    <modules>
        <Mycode_Function>
            <version>1.0.0</version>
        </Mycode_Function>
    </modules>
 
    <global>
 
        <helpers>
            <function>
                <class>Mycode_Function_Helper</class>
            </function>
        </helpers> 
 
    </global>
 
</config>

3) Create the directory
app/code/local/Mycode/Function/Helper
and then create a file named ‘Data.php’
In it copy:

<?php
 
class Mycode_Function_Helper_Data extends Mage_Core_Helper_Abstract
{
 
	public function test(){
 
	return 'works';
 
	}
 
}

You can now call this function like so

		<?php 
 
		 echo Mage::helper('function')->test();
 
		 ?>

6 Comments on “Create Global Function In Magento”

  1. 1 Martin Kristan said at 8:43 am on September 27th, 2011:

    Correct is:

    echo Mage::helper(‘mycode/function’)->test();

  2. 2 Custom Global Functions in Magento, Magento Blog and E-Commerce said at 7:55 am on January 4th, 2012:

    [...] in their site. Before I start I should give credit for this post to Joe Riggs for his post here: http://joe-riggs.com/blog/2011/06/create-global-function-in-magento/ – it gives a nice tutorial on how to include your own custom functions in Magento by simply [...]

  3. 3 kalyan said at 6:42 am on June 25th, 2012:

    this is the right way to call the helper

    Mage::helper(‘mycodefunction’)->test();

    to display the result

    echo Mage::helper(‘mycodefunction’)->test();

  4. 4 bones said at 2:48 am on October 19th, 2012:

    uhm,.. all i’m seeing are corrections, can you guys post the whole “CORRECT” code for beginners like me? thanks

  5. 5 jriggs said at 8:00 am on October 19th, 2012:

    Hi Bones, this is the exact code I used on a project and it worked….I never bothered to test the ‘corrections’ others have posted, but I left them in case it would help someone else…If you have any doubts, check here: http://www.e-commercewebdesign.co.uk/blog/magento-tips/custom-global-functions-in-magento.php

    I would think this site has much more traffic than my own, and if there were faults in the code it would have been pointed out by now. Good Luck!

  6. 6 Josh said at 2:08 pm on February 15th, 2014:

    IR


Leave a Reply