The wc_get_template filter is a powerful tool in the WordPress developer’s arsenal. It allows you to intercept the template loading process and redirect WooCommerce to use a custom file instead of the default one.
When using the Donation Platform for WooCommerce, you can use this filter to customize not only standard WooCommerce elements (like the cart or checkout) but also the specific donation templates provided by our plugin.
TL;DR
- Prerequisites: Proficiency in PHP, HTML, JavaScript, and CSS.
- Core Function: Dynamically changes the file path of a template before it is rendered.
- Flexibility: Works for both core WooCommerce templates and Donation Platform templates.
How it Works
The filter passes several arguments that help you identify exactly which template is being called. By checking the $template_name, you can conditionally swap the $located path with your own custom file path.
The Filter Structure
apply_filters( 'wc_get_template', $located, $template_name, $args, $template_path, $default_path );| Parameter | Description |
$located | The resolved path to the template file. |
$template_name | The name of the template (e.g., checkout/form-pay.php). |
$args | Array of variables passed to the template. |
$template_path | The template path (usually ‘woocommerce/’). |
$default_path | The default path to the template directory. |
Implementation Example
Suppose you want to override the donation form template specifically when a certain condition is met. You would add the following code to your child theme’s functions.php or a custom functional plugin.
add_filter( 'wc_get_template', 'custom_donation_template_override', 10, 5 );
function custom_donation_template_override( $located, $template_name, $args, $template_path, $default_path ) {
// Check for the specific Donation Platform template
if ( 'wcdp_form_style_3.php' === $template_name ) {
// Define the path to your custom template within your child theme
$overridden_template = get_stylesheet_directory() . '/my-custom-donations/amount-input.php';
// Ensure the file exists before overriding
if ( file_exists( $overridden_template ) ) {
return $overridden_template;
}
}
return $located;
}
Important Considerations
- Priority: If you are using multiple plugins that hook into
wc_get_template, pay attention to the priority (the10in the example above). A higher number runs later. - Performance: This filter runs every time a template is loaded. Keep your logic inside the function lightweight to avoid slowing down the site.
- Version Control: When overriding templates, remember to check for updates in the original plugin. If the base template is updated with new functionality or security patches, you may need to update your custom file accordingly.
Pro Tip: While
wc_get_templateis great for logic-based overrides, if you simply want to change the look of a template permanently, it is often easier to use the standard WooCommerce Template Override system by copying the file into your theme folder.
