Manual:Parser functions

Jump to: navigation, search
Gnome-preferences-other.svg Extensions: Development Tag extensions Parser functions Hooks Special pages Skins Magic words API
MediaWiki extensions

Parser functions, added in MediaWiki 1.7, are a type of extension that integrate closely with the parser. The phrase "parser function" should not be confused with Extension:ParserFunctions, which is a collection of simple parser functions. (See Help:Extension:ParserFunctions for those.)

Description[edit | edit source]

Whereas a Tag extension is expected to take unprocessed text and return HTML to the browser, a parser function can 'interact' with other wiki elements in the page. For example, the output of a parser function could be used as a template parameter or in the construction of a link.

The typical syntax for a parser function is:

{{ #functionname: param1 | param2 | param3 }}

For more information, see the documentation for Parser::setFunctionHook ( $id, $callback, $flags = 0 ). This documentation states:

The callback function should have the form:
function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
Or with SFH_OBJECT_ARGS: function myParserFunction( $parser, $frame, $args ) { ... }"

Creating a parser function is slightly more complicated than creating a new tag because the function name must be a magic word, a keyword that supports aliases and localization.

Simple example[edit | edit source]

Below is an example of an extension that creates a parser function.

This file should be called ExampleExtension.php if the name of your extension is ExampleExtension:

// Take credit for your work.
$wgExtensionCredits['parserhook'][] = array(
   // The full path and filename of the file. This allows MediaWiki
   // to display the Subversion revision number on Special:Version.
   'path' => __FILE__,
   // The name of the extension, which will appear on Special:Version.
   'name' => 'Example Parser Function',
   // A description of the extension, which will appear on Special:Version.
   'description' => 'A simple example parser function extension',
   // Alternatively, you can specify a message key for the description.
   'descriptionmsg' => 'exampleextension-desc',
   // The version of the extension, which will appear on Special:Version.
   // This can be a number or a string.
   'version' => 1, 
   // Your name, which will appear on Special:Version.
   'author' => 'Me',
   // The URL to a wiki page/web page with information about the extension,
   // which will appear on Special:Version.
   'url' => '',
// Specify the function that will initialize the parser function.
$wgHooks['ParserFirstCallInit'][] = 'ExampleExtensionSetupParserFunction';
// Allow translation of the parser function name
$wgExtensionMessagesFiles['ExampleExtension'] = __DIR__ . '/ExampleExtension.i18n.php';
// Tell MediaWiki that the parser function exists.
function ExampleExtensionSetupParserFunction( &$parser ) {
   // Create a function hook associating the "example" magic word with the
   // ExampleExtensionRenderParserFunction() function. See: the section 
   // 'setFunctionHook' below for details.
   $parser->setFunctionHook( 'example', 'ExampleExtensionRenderParserFunction' );
   // Return true so that MediaWiki continues to load extensions.
   return true;
// Render the output of the parser function.
function ExampleExtensionRenderParserFunction( $parser, $param1 = '', $param2 = '', $param3 = '' ) {
   // The input parameters are wikitext with templates expanded.
   // The output should be wikitext too.
   $output = "param1 is $param1 and param2 is $param2 and param3 is $param3";
   return $output;

Another file, ExampleExtension.i18n.php, should contain:

 * @since 1.0.0
 * @file
 * @licence GNU GPL
 * @author Your Name (YourUserName)
$magicWords = array();
/** English
 * @author Your Name (YourUserName)
$magicWords['en'] = array(
   'example' => array( 0, 'example' ),

With this extension enabled,

  • {{#example: hello | hi | hey}}


  • param1 is hello and param2 is hi and param3 is hey

Note: This magicWords array is not optional. If it is omitted, the parser function simply will not work; the {{#example: hello | hi}} will be rendered as though the extension were not installed.

Longer functions[edit | edit source]

For longer functions, you may want to split the hook functions out to a _body.php or .hooks.php file and make them static functions of a class. Then you can load the class with $wgAutoloadClasses and call the static functions in the hooks; e.g.:

Put this in your MyExtension.php file:

$wgAutoloadClasses['MyExtensionHooks'] = "$dir/MyExtension.hooks.php";
$wgHooks[' ... '][] = 'MyExtensionHooks::MyExtensionFunction';

Then put this is in your MyExtension.hooks.php file:

class MyExtensionHooks {
      public static function MyExtensionFunction( ... ) {
           $parser->setFunctionHook( 'example',
                'MyExtensionHooks::ExampleExtensionRenderParserFunction' );

Caching[edit | edit source]

As with tag extensions, $parser->disableCache() may be used to disable the cache for dynamic extensions.

Parser interface[edit | edit source]

Controlling the parsing of output[edit | edit source]

To have the wikitext returned by your parser function be fully parsed (including expansion of templates), set the noparse option to false when returning:

return array( $output, 'noparse' => false );

It seems the default value for noparse changed from false to true, at least in some situations, sometime around version 1.12.

Conversely, to have your parser function return HTML that remains unparsed, rather than returning wikitext, use this:

return array( $output, 'noparse' => true, 'isHTML' => true );


This is {{#example:hello | hi | hey }} a test.

will produce something like this:

This is

param1 is hello and param2 is hi and param3 is hey a test.

This happens due to a hardcoded "\n\n" that is prepended to the HTML output of parser functions. To avoid that and make sure the HTML code is rendered inline to the surrounding text, you can use this:

return $parser->insertStripItem( $output, $parser->mStripState );

Naming[edit | edit source]

By default, MW adds a hash character (number sign, "#") to the name of each parser function. To suppress that addition (and obtain a parser function with no "#" prefix), include the SFH_NO_HASH constant in the optional flags argument to setFunctionHook, as described below.

When choosing a name without a hash prefix, note that transclusion of a page with a name starting with that function name followed by a colon is no longer possible. In particular, avoid function names equal to a namespace name. In the case that interwiki transclusion [1] is enabled, also avoid function names equal to an interwiki prefix.

The setFunctionHook hook[edit | edit source]

For more details of the interface into the parser, see the documentation for setFunctionHook in includes/Parser.php. Here's a (possibly dated) copy of those comments:

function setFunctionHook( $id, $callback, $flags = 0 )


  • string $id - The magic word ID
  • mixed $callback - The callback function (and object) to use
  • integer $flags - Optional, set it to the SFH_NO_HASH constant to call the function without "#".

Return value: The old callback function for this name, if any

Create a function, e.g., {{#sum:1|2|3}}. The callback function should have the form:

function myParserFunction( $parser, $arg1, $arg2, $arg3 ) { ... }

The callback may either return the text result of the function, or an array with the text in element 0, and a number of flags in the other elements. The names of the flags are specified in the keys. Valid flags are:

The text returned is valid, stop processing the template. This is on by default.
Wiki markup in the return value should be escaped
Unsafe HTML tags should not be stripped, etc.
Don't replace triple-brace arguments in the return value
The returned text is HTML, armour it against wikitext transformation

Named parameters[edit | edit source]

Parser functions do not support named parameters the way templates and tag extensions do, but it is occasionally useful to fake it. Users are often accustomed to using vertical bars ( | ) to separate arguments, so it's nice to be able to do that in the parser function context, too. Here's a simple example of how to accomplish this.

Mixing positional parameters with this named parameter technique is fraught with peril! Your life will be significantly improved if you stick with one or the other.

Your callback function typically looks like this:

function ExampleExtensionRenderParserFunction( $parser, $arg1, $arg2, ..., $argn )

To fake named parameters, simply omit all the arguments after $parser, and pair it with func_num_args(). Here is an example:

function ExampleExtensionRenderParserFunction( $parser ) {
	//Suppose the user invoked the parser function like so:
	$opts = array();
	// Argument 0 is $parser, so begin iterating at 1
	for ( $i = 1; $i < func_num_args(); $i++ ) {
		$opts[] = func_get_arg( $i );
	//The $opts array now looks like this:
	//	[0] => 'foo=bar'
	//	[1] => 'apple=orange'
	//Now we need to transform $opts into a more useful form...
	$options = extractOptions( $opts );
	#Continue writing your code...
 * Converts an array of values in form [0] => "name=value" into a real
 * associative array in form [name] => value
 * @param array string $options
 * @return array $results
function extractOptions( array $options ) {
	$results = array();
	foreach ( $options as $option ) {
		$pair = explode( '=', $option, 2 );
		if ( count( $pair ) == 2 ) {
			$name = trim( $pair[0] );
			$value = trim( $pair[1] );
			$results[$name] = $value;
	//Now you've got an array that looks like this:
	//	[foo] => bar
	//	[apple] => orange
	return $results;

See also[edit | edit source]

Language: English  • dansk • Deutsch • Bahasa Indonesia • 日本語 • русский