Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
class MyTimber extends TimberSite {
function __construct() {
add_filter( 'timber_context', [$this, 'add_to_context'] );
add_filter( 'get_twig', [$this, 'add_to_twig'] );
parent::__construct();
}
// Add Global variable
function add_to_context( $context ) {
// Site's settings like site.title
$context['site'] = $this;
$context['home_url'] = home_url();
// Menu - Timber stored it as an array so you can loop it and write custom markup
$context['nav'] = new TimberMenu( 'main-nav' );
// Link to the image inside your theme
// Example: <img src="{{ images }}/logo.svg">
$context['images'] = get_template_directory_uri() . '/images';
// Footer Widget - for post widget, no need to be global
$context['footer_widgets'] = Timber::get_widgets( 'footer_widgets' );
// ACF Options Page, if you have one
if( function_exists( 'acf_add_options_page' )) {
$context['options'] = get_fields( 'options' );
}
// WooCommerce, if installed
if( class_exists('WooCommerce') ) {
global $woocommerce;
$context['woo'] = $woocommerce;
}
return $context;
}
function add_to_twig( $twig ) {
$twig->addFilter( new Twig_SimpleFilter( 'my_example', [$this, 'filter_my_example'] ) );
$twig->addFilter( new Twig_SimpleFilter( 'my_example2', [$this, 'filter_my_example2'] ) );
return $twig;
}
/**
* Basic custom filter
*
* {{ post.content | my_example }}
*/
function filter_my_example( $value ) {
// do something
return $value;
}
/**
* Has passed argument
*
* {{ post.content | my_example2( 'arg' ) }}
*/
function filter_my_example2( $value, $arg ) {
// do something
return $value;
}
}
new MyTimber(); // call the class
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment