🧩Twig Extensions
Twig extensions let you add custom functions, filters, and globals to the Twig templating environment. They're the rigging of your PressGang ship — connecting the PHP engine room to the Twig deck where templates do their work.
How They Work
All Twig extensions are managed through extension manager classes that implement the TwigExtensionManagerInterface. These managers are registered in config/twig-extensions.php and wired up during boot by the TimberServiceProvider.
The Interface
namespace PressGang\TwigExtensions;
use Twig\Environment;
interface TwigExtensionManagerInterface {
public function add_twig_functions(Environment $twig): void;
public function add_twig_filters(Environment $twig): void;
public function add_twig_globals(Environment $twig): void;
}Each method receives the Twig Environment and can register any number of functions, filters, or globals.
Convenience Traits
If your extension only needs to implement one or two of the three methods, PressGang provides no-op traits to keep your code clean:
HasNoFunctions— provides an emptyadd_twig_functions().HasNoFilters— provides an emptyadd_twig_filters().HasNoGlobals— provides an emptyadd_twig_globals().
Built-in Extension Managers
GeneralExtensionManager
Registers general-purpose functions and globals:
Functions:
get_search_query()— returns the current search query string.get_option(name)— retrieves a WordPress option.get_theme_mod(name)— retrieves a theme modification value.
Globals:
THEMENAME— the text domain constant, for use in translation calls.
MetaDescriptionExtensionManager
Functions:
meta_description()— generates an SEO-friendly meta description for the current page, via theMetaDescriptionService.
See SEO for details on the meta description fallback chain.
SinglePostExtensionManager
Only active on single post pages. Requires the post to be mapped to PressGang\Post via the timber-class-map config.
Functions:
get_latest_posts(count)— fetches the latest posts (excluding the current one).get_related_posts(count)— fetches posts related to the current one by shared taxonomy terms.
WidgetExtensionManager
Registers a Twig function for rendering WordPress widgets in templates.
WooCommerceExtensionManager
Registers WooCommerce-specific Twig functions when WooCommerce is active.
Creating a Custom Extension Manager
Rules for Twig Functions
Twig is for presentation only. Keep your Twig functions pure and side-effect free!
No database queries — if you need data, provide it via a controller or context manager.
No writes — no
update_option(),wp_insert_post(), or similar.No remote requests — no
wp_remote_get()or API calls.Deterministic — same inputs should always produce the same outputs.
Pure — no side effects, no mutation of global state.
Last updated