From 80cb4f3808bfa4bd9f6a056e551db6fbbe2a6c8b Mon Sep 17 00:00:00 2001 From: Ben Voynick Date: Tue, 9 Jul 2019 16:43:08 -0400 Subject: [PATCH] Put initialization code in a function, so that the function can be called later if Wordpress and the add_filter function are not initialized when package is loaded --- README.md | 15 ++++++++++++--- functions.php | 35 +++++++++++++++++++++++++---------- 2 files changed, 37 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index c0c0ce0..e54c22d 100644 --- a/README.md +++ b/README.md @@ -22,6 +22,15 @@ composer require djboris88/timber-commented-include --dev Usage ----- -To be able to see the commented output, `WP_DEBUG` has to be defined and set as -`true` in `wp-config.php` file. The Twig Extension will automatically be registered -and applied. +To be able to see the commented output, `WP_DEBUG` has to be defined and set as +`true` in `wp-config.php` file. + +The Twig Extension will automatically be registered and applied. If the +WordPress add_filter function is not available when that happens, it will fail. +In that case, you will need to call initialization yourself at an appropriate +time after WordPress itself is initialized: +```php +if (function_exists('\Djboris88\Timber\initialize_filters')) { + \Djboris88\Timber\initialize_filters(); +} +``` diff --git a/functions.php b/functions.php index dbe27e3..06867fd 100644 --- a/functions.php +++ b/functions.php @@ -24,14 +24,29 @@ function add_commented_include_extension($twig) return $twig; } -if (defined('WP_DEBUG') && WP_DEBUG && function_exists('add_filter')) { - add_filter('timber/loader/twig', sprintf('%s\\add_commented_include_extension', __NAMESPACE__)); - - /** - * Adding a second filter to cover the `Timber::render()` case, when the - * template is not loaded through the `include` tag inside a twig file - */ - add_filter( 'timber/output', function( $output, $data, $file ) { - return "\n\n" . $output . "\n\n"; - }, 10, 3 ); +/** + * Tries to initialize the twig extension, if it has not been already. + */ +function initialize_filters() +{ + if ( + !defined('WP_DJBORIS88_TIMBER_FILTERS_INITIALIZED') + && defined('WP_DEBUG') + && WP_DEBUG + && function_exists('add_filter') + ) { + define('WP_DJBORIS88_TIMBER_FILTERS_INITIALIZED', TRUE); + + add_filter('timber/loader/twig', sprintf('%s\\add_commented_include_extension', __NAMESPACE__)); + + /** + * Adding a second filter to cover the `Timber::render()` case, when the + * template is not loaded through the `include` tag inside a twig file + */ + add_filter( 'timber/output', function( $output, $data, $file ) { + return "\n\n" . $output . "\n\n"; + }, 10, 3 ); + } } + +initialize_filters();