Skip to content

Instantly share code, notes, and snippets.

@obiPlabon
Last active September 26, 2020 12:50
Show Gist options
  • Save obiPlabon/3ef0ee67bec90767867a827e694c5313 to your computer and use it in GitHub Desktop.
Save obiPlabon/3ef0ee67bec90767867a827e694c5313 to your computer and use it in GitHub Desktop.
Helper class to override WooCommerce templates from plugin
<?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();
@ta-riq
Copy link

ta-riq commented Mar 25, 2018

Thank you Sir.

@obiPlabon
Copy link
Author

@ta-riq thanks bro 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment