Add WooCommerce-to-Twig rendering bridge

Intercept WooCommerce's PHP template loading via
woocommerce_before_template_part / woocommerce_after_template_part hooks
to render Bootstrap 5 Twig templates instead. This makes all 99 child
theme templates functional in a standard WooCommerce environment.

- Create WooCommerceExtension (Twig AbstractExtension) with ~50 functions
  and 7 filters covering WC API, WordPress hooks, escaping, and forms
- Rewrite TemplateOverride to use hook-based interception with stack-based
  output buffering for nested template support
- Wire bridge initialization at init priority 20 in functions.php
- Fix invalid {% do return() %} in two order templates

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-02-28 11:15:59 +01:00
parent 49b1d52701
commit 46eb7f0a22
5 changed files with 538 additions and 136 deletions

View File

@@ -43,16 +43,42 @@ function wc_bootstrap_setup(): void {
add_action( 'after_setup_theme', 'wc_bootstrap_setup' );
/**
* Register plugin template overrides.
* Initialize the WooCommerce-to-Twig template bridge.
*
* Prepends the child theme's templates/ directory to the plugin's Twig loader,
* so child theme templates take priority over plugin templates.
* Registers the WooCommerce Twig extension with the parent theme's TwigService
* and sets up template interception hooks so the child theme's Twig templates
* are rendered instead of WooCommerce's PHP templates.
*
* Runs at 'init' priority 20 to ensure WooCommerce is fully loaded (it
* initializes at 'init' priority 0).
*/
function wc_bootstrap_register_template_override(): void {
function wc_bootstrap_init_twig_bridge(): void {
// Guard: require parent TwigService and WooCommerce.
if ( ! class_exists( '\WPBootstrap\Twig\TwigService' ) || ! function_exists( 'WC' ) ) {
return;
}
$twig = \WPBootstrap\Twig\TwigService::getInstance();
$env = $twig->getEnvironment();
// Add child theme templates directory to the Twig loader so {% include %}
// directives in Twig templates can find other child theme templates.
$loader = $env->getLoader();
if ( $loader instanceof \Twig\Loader\FilesystemLoader ) {
$template_dir = WC_BOOTSTRAP_PATH . 'templates';
if ( is_dir( $template_dir ) ) {
$loader->prependPath( $template_dir );
}
}
// Register WooCommerce functions and filters as Twig extensions.
$env->addExtension( new \WcBootstrap\Twig\WooCommerceExtension() );
// Register template interception hooks.
$override = new \WcBootstrap\TemplateOverride();
$override->register();
}
add_action( 'after_setup_theme', 'wc_bootstrap_register_template_override' );
add_action( 'init', 'wc_bootstrap_init_twig_bridge', 20 );
/**
* Enqueue child theme styles.