Last active
September 26, 2020 12:50
-
-
Save obiPlabon/3ef0ee67bec90767867a827e694c5313 to your computer and use it in GitHub Desktop.
Helper class to override WooCommerce templates from plugin
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
<?php | |
/** | |
* WooCommerce template overriding class | |
* | |
* @author obiPlabon | |
*/ | |
class WC_Template_Override { | |
/** | |
* Templates map | |
* Templates that you want to => with override | |
* | |
* @var array | |
*/ | |
private static $templates = []; | |
/** | |
* Template directory in theme | |
* | |
* Theme authors can also override your override ;) :P | |
* Add a convenient name instead of just "override" | |
* | |
* @return string | |
*/ | |
private static function get_template_path() { | |
return WC()->template_path() . 'override/'; | |
} | |
/** | |
* Templates directory in plugin | |
* | |
* Usually you'll put all of your overriding templates in tempaltes directory | |
* | |
* @return string | |
*/ | |
private static function get_template_default_path() { | |
// Make sure you're returning coreect directory path | |
return plugin_dir_path( __FILE__ ) . 'templates/'; | |
} | |
/** | |
* Initialize the process | |
* | |
* @return void | |
*/ | |
public static function init() { | |
// Setup templates map | |
self::$templates = [ | |
'single-product/title.php' => 'common/title.php', | |
'single-product/price.php' => 'common/price.php', | |
]; | |
add_filter( 'woocommerce_locate_template', [ __CLASS__, 'override' ], 10, 3 ); | |
} | |
/** | |
* Override WooCommerce default template | |
* | |
* @param string $template | |
* @param string $template_name | |
* @param string $template_path | |
* @return string | |
*/ | |
public static function override( $template, $template_name, $template_path ) { | |
// Return early if it's not the template you targeted | |
if ( ! array_key_exists( $template_name, self::$templates ) ) { | |
return $template; | |
} | |
// Remove this filter hook callback to prevent recursive call | |
remove_filter( 'woocommerce_locate_template', [ __CLASS__, __FUNCTION__ ] ); | |
// Return new template | |
return wc_locate_template( | |
self::$templates[ $template_name ], | |
self::get_template_path(), | |
self::get_template_default_path() | |
); | |
} | |
} | |
WC_Template_Override::init(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@ta-riq thanks bro 👍