1

I've been trying to apply a filter to WooCommerce from inside my own custom plugin but whatever I do, the filter is not firing.

The commonly found solutions online don't work. I've tried:

I've also tried to attach the filter to various action points (init, plugins_loaded) and various priorities (10, 20, 999).

To test I've created a simple one-page plugin. When the filter fires it should write to error_log. The file is in /wp-content/plugins/plugintest.php

<?php
/*
 * Plugin Name: Plugin TEST
 * Description: A simple plugin to test
 * Version: 1.0
**/

function my_test_get_template( $template, $template_name, $args ) {    

    error_log('working ...... FILTER ....  ');

    return $template;
}


error_log('working ... ');

add_filter( 'woocommerce_locate_template', 'my_test_get_template', 20, 3);  

However the error_log inside the filter never gets written, the output is simply

[15-Oct-2019 16:20:52 UTC] working ... 

I don't understand why the code is not working. I know that WooCommerce is active and working as the other code I wrote (which extends the WC_EMAIL class) is fine. And I can filter "woocommerce_email_classes" without any issues, that's also working. But the template path won't fire. Anything obvious I'm doing wrong?

Will
  • 413
  • 6
  • 23
E Allison
  • 51
  • 6

1 Answers1

0

So I didn't get the filter to work but I found a workaround. Instead of applying a filter to the path, in the email class I added a template base which checks if there's a file in the theme, if not it uses the plugin file. This allows overriding of the plugin template via theme.

In the construct call of the custom WooCommerce email I added:

$this->template_base  = $this->get_template_path();

which calls this function:

public function get_template_path() {

// are we looking for html or plain?
$template = ($this->get_option( 'email_type' ) == 'html') ? $this->template_html : $this->template_plain;

// path to theme woocommerce file overrides 
$theme_path = get_stylesheet_directory() . '/woocommerce/'; 

//plugin path 
$plugin_path = plugin_dir_path( dirname( __FILE__ ) )  . 'templates/';

// if we have a theme file let's use it, otherwise revert to plugin file
$path = (file_exists($theme_path . $template) ) ? $theme_path : $plugin_path;

return $path;       

}

This now works. It's specific to email template paths but that's all I needed.

E Allison
  • 51
  • 6