Created
December 8, 2019 12:11
-
-
Save hrsetyono/7bf65b9a8e3239983f0f11c985338295 to your computer and use it in GitHub Desktop.
Code sample from https://wptips.dev/global-var-n-filters-in-timber/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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