Smarty templates: Creating smarty custom functions

smarty-custom-functionYesterday I wrote an article about a php method that can convert normal timestamp into “x Min Ago” like timestamps. I will call these type of timestamps an “agots“. Although the PHP method is straight forward in converting unix timestamps to agotimestamps, I thought of implementing a custom function in smarty that can be used anywhere in your smarty template to generate agots. Let us first see the basics of Smarty Custom Functions.

What is Custom Function in Smarty?

Smarty comes with lots of inbuilt functions that can be used in our smarty templates and that provides rich set of APIs that can leveraged for easy creation of UI. Although sometimes we may need to create our own functionality and plug it in smarty so that it can be used across all smarty projects. So we can create our own custom smarty functions. Custom functions are nothing but a normal PHP function with a given function name and written in a given filename. We will see in next sections how exactly to write a custom function in smarty.

Creating a Custom Function

As mentioned in previous section, creating custom function in smarty is straightforward. Follow the three steps process and there you have your own smarty custom function.

Step 1: Name the plugin and add a Header

Create an empty PHP file and add a commented header to the PHP file. In our case the custom function name will be agots, so following will be the header.
/* * Smarty plugin * ------------------------------------------------------------- * File: function.agots.php * Type: function * Name: agots * Description: This TAG creates a "x minute ago" like timestamp. * * ------------------------------------------------------------- * @license GNU Public License (GPL) * * ------------------------------------------------------------- * Parameter: * - ts = the email to fetch the gravatar for (required) * ------------------------------------------------------------- * Example usage: * * <div>{agots ts="3434323"} ago </div> */
Code language: PHP (php)
In above header, the Name: attribute is the name of your custom function and the File: attribute is the file name where you are writing this function.

Step 2: Write your PHP custom function

Once the header is ready, all you have to do is write the PHP function. In our case we have written agots function. One thing you have to take care here is that all smarty custom function names must start with “smarty_function_“. Thus our agots function’s name will be smarty_function_agots. Also all smarty custom functions must be defined with two parameters $params and &$smarty. The parameters that we pass in custom functions can be read through the associative array $params. In our case the parameter will be timestamp (ts) so we read this parameter as $params['ts'] in our custom function.
function smarty_function_agots($params, &$smarty) { if(!isset($params['ts'])) { $smarty->trigger_error("gravatar: neither 'email' nor 'default' attribute passed"); return; } //return $params['ts']; // array of time period chunks $chunks = array( array(60 * 60 * 24 * 365 , 'year'), array(60 * 60 * 24 * 30 , 'month'), array(60 * 60 * 24 * 7, 'week'), array(60 * 60 * 24 , 'day'), array(60 * 60 , 'hour'), array(60 , 'min'), array(1 , 'sec'), ); $today = time(); /* Current unix time */ $since = $today - $params['ts']; // $j saves performing the count function each time around the loop for ($i = 0, $j = count($chunks); $i < $j; $i++) { $seconds = $chunks[$i][0]; $name = $chunks[$i][1]; // finding the biggest chunk (if the chunk fits, break) if (($count = floor($since / $seconds)) != 0) { break; } } $print = ($count == 1) ? '1 '.$name : "$count {$name}s"; if ($i + 1 < $j) { // now getting the second item $seconds2 = $chunks[$i + 1][0]; $name2 = $chunks[$i + 1][1]; // add second item if its greater than 0 if (($count2 = floor(($since - ($seconds * $count)) / $seconds2)) != 0) { $print .= ($count2 == 1) ? ', 1 '.$name2 : " $count2 {$name2}s"; } } return $print; } [/code] <h3>Step 3: Save the custom function in Plugins directory</h3> We are ready to deploy our custom function to Smarty. All you have to do is just copy the PHP file function.agots.php to <strong>plugins</strong> directory in smarty installation directory. Just make sure that the name of the plugin file is same as the name specified in file header. The good practice is to have name as function.<custom_function>.php. <h2>Calling the custom function</h2> To call your new function, you simply reference it by its name within curly brackets. And if the function requires a parameter, like ours does, youd call it like this: <!-- wp:code {"language": "php"} --><pre class="wp-block-code"><code></code></pre><!-- /wp:code --> {agots ts='2451254'}
Code language: PHP (php)
You may want to pass the value of smarty variable to our custom function.
{agots ts=$myunixtimestamp}
Code language: PHP (php)
Above is a simple example to create your own custom function in smarty. You may extend this and add your own useful functions. You may want to bookmark this article and share it with others.
Get our Articles via Email. Enter your email address.

You may also like...


  1. Php says:

    Very good one. Cool :-)

  2. I want to add meta tag’s keywords and description attributes dynamically.

    First I done it within and assigned the variables in template files.

    But after creating smarty function i can use it like:

    function smarty_function_metatag($params, &$smarty) {

    if(!isset($params[‘tmpl’])) {
    $smarty->trigger_error(“metatag: parameter ‘tmpl’ missing”);
    else if(!isset($params[‘ttype’])) {
    $smarty->trigger_error(“metatag: parameter ‘ttype’ missing”);

    $pfile = $params[‘tmpl’];

    switch ($params[‘ttype’]) {

    case ‘keywords’:

    $array_keywords = array(
    ‘contact’=>’Contact Us,Extentia’,
    ‘forgot’=>’Forgot Password,Extentia’

    if (array_key_exists($pfile, $array_keywords)) {
    return $array_keywords[$pfile];


    case ‘description’:

    $array_description = array(
    ‘login’=>’Login to Extentia,Extentia’,
    ‘faq’=>’FAQ about Extentia,Extentia’,
    ‘news’=>’News about Extentia,Extentia’,
    ‘contact’=>’Contact Us,Extentia’,
    ‘careers’=>’Careers at Extentia,Extentia’,
    ‘forgot’=>’Forgot Password,Extentia’,

    if (array_key_exists($pfile, $array_description)) {
    return $array_description[$pfile];


    Your post helped me a lot.

    Thank you Viral Patel.

  3. Use above function like:

  4. Craig says:

    Thanks…I couldn’t remember the correct syntax. This is easier to understand than the smarty manual for this topic.

  5. Craig says:

    BTW, Section 2 of your example in the function definition, the ampersand is getting rendered as its “&’ entity form which might confuse someone new to PHP/smarty wondering why your example won’t work.

  6. Crystal Wilson says:

    This is awesome, you have saved me so much time and didn’t realize how easy it was to create Smarty plugin! Thank you.

  7. zyli says:

    i have listings.html, header.html
    and created myfunction in
    i created a function in libs/plugins
    when i use it in listings.html is working but in header.html just give me an empty space. any ideea why?

  8. Keny says:

    Nice man :)

  9. AQAA says:

    How to write this one ?

    //echo $url;
    echo $this->_tpl_vars['myobj']->getTpl('general','header1.tpl');
    echo $this->_tpl_vars['myobj']->getTpl('general','header.tpl');

  10. transistor says:

    I had to modify a shopping cart application built on smarty. Never used it before. With this tutorial I was quickly able to write a function to pull some info from the database and return it in the function. Many thanks.

  11. Gomathi says:

    Immediately I want forget password coding in smarty with database pleeeeeeeeeeee

Leave a Reply

Your email address will not be published. Required fields are marked *