【问题标题】:How can I apply a filter from another plugin to woocommerce?如何将另一个插件的过滤器应用于 woocommerce?
【发布时间】:2019-10-15 16:29:08
【问题描述】:

我一直在尝试从我自己的自定义插件中对 WooCommerce 应用过滤器,但无论我做什么,过滤器都不会触发。

网上常见的解决方案不起作用。我试过了:

我还尝试将过滤器附加到各种操作点(init、plugins_loaded)和各种优先级(10、20、999)。

为了测试,我创建了一个简单的单页插件。当过滤器触发时,它应该写入error_log。该文件位于/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);  

但是过滤器内部的error_log永远不会被写入,输出只是

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

我不明白为什么代码不起作用。我知道 WooCommerce 是活跃的,并且可以像我编写的其他代码(扩展 WC_EMAIL 类)一样工作。而且我可以毫无问题地过滤“woocommerce_email_classes”,这也有效。但是模板路径不会触发。有什么明显的我做错了吗?

【问题讨论】:

    标签: php wordpress woocommerce


    【解决方案1】:

    所以我没有让过滤器工作,但我找到了解决方法。我没有对路径应用过滤器,而是在电子邮件类中添加了一个模板库,它检查主题中是否有文件,如果没有,则使用插件文件。这允许通过主题覆盖插件模板。

    在我添加的自定义 WooCommerce 电子邮件的构造调用中:

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

    调用这个函数:

    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;       
    

    }

    现在可以了。它特定于电子邮件模板路径,但这就是我所需要的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-02
      • 1970-01-01
      • 2011-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多