Skip to content

Develop your custom extension

Takayuki Miyauchi edited this page Nov 26, 2015 · 4 revisions

You can develop your custom twig extension like following

Create a extension as plugin

<?php
/*
Plugin Name: My Twig Extension
*/

// Create a extension as class
class My_Twig_Extension extends \Twig_Extension
{
    public function getFunctions()
    {
        $functions = array();
        $functions[] = new \Twig_SimpleFunction(
            'get_my_posts',
            array( $this, 'get_my_posts' ), 
            array( 'is_safe' => array( 'all' ) ) 
        );
    }

    public function get_my_posts( $args = array() )
    {
        $posts = get_posts( $args );
        return do_something( $posts );
    }

    public function getName()
    {
        return 'my-custom-extension';
    }
}

// Register your custom extension
add_filter( 'content_template_engine_twig_extensions', function( $extensions ){
    $extensions[] = new My_Twig_Extension(); // your extension's class
    return $extensions;
} );

Then you can use this extension in your contents like following.

<ul>
{% for p in get_my_posts( ... ) %}
  <li>{{ p.post_title }}</li>
{% endfor %}
</ul>

See also:

Getting Started

For Designers

For Developers

  • [Filter Hooks](Filter Hooks)
  • [Develop your custom extension](Develop your custom extension)
Clone this wiki locally