WooCommerce Extensions: Serve custom templates

2023-10-31 | WooCommerce

Define the function that performs the intercept.

/**
 * Serve custom template files instead of the default WooCommerce ones.
 *
 * @param string $template Template.
 * @param string $template_name Template name.
 * @param string $template_path Template path.
 * @return string The custom template file path.
 */
function intercept_wc_locate_template( $template, $template_name, $template_path ) {
	/**
	 * $tempalte_dir holds the path to the directory containing the custom templates.
	 *
	 * ```php
	 * $template_dir = untrailingslashit( plugin_dir_path( dirname( __FILE__ ) ) );
	 * ```
	 */
	$template_dir = '! DEFINE THE PATH HERE !';
	$path         = "{$template_dir}/{$template_name}";

	return file_exists( $path ) ? $path : $template;
}

Hook into the wc_locate_template()

add_filter( 'woocommerce_locate_template', 'intercept_wc_locate_template', 10, 3 );