【问题标题】:variable scope in woocommerce filterwoocommerce过滤器中的变量范围
【发布时间】:2017-03-29 13:29:44
【问题描述】:

我的页面需要在管理员的 woocommerce 电子邮件中显示不同的产品名称(新客户订单电子邮件)。要更改名称,我使用过滤器 woocommerce_order_item_name。 但我必须验证它是管理员电子邮件还是客户电子邮件。我在这段代码中使用了一个 gloab 变量,它可以工作,但我猜这不是正确的方式。那么有没有更好的解决方案来验证它是管理员电子邮件还是客户电子邮件?

woocommerce/emails/email-order-items.php

global $is_admin_email;
if($show_sku) {
    $is_admin_email = True;
}
else {
    $is_admin_email = False;

// Product name
echo apply_filters( 'woocommerce_order_item_name', $item['name'], $item, false );
//Set to false again
$is_admin_email = False;

functions.php

function filter_woocommerce_order_item_name( $item_name, $item, $false ) { 
    global $is_admin_email;
    if( $is_admin_email ){
        $item_name = "Item name in admin email";
    }

    return $item_name; 
};

// add the filter
add_filter( 'woocommerce_order_item_name', 'filter_woocommerce_order_item_name', 10, 3 );

【问题讨论】:

    标签: php wordpress woocommerce


    【解决方案1】:

    我会找到一个显示在电子邮件中的钩子,其中包含变量$sent_to_admin,当发送给管理员时它是true。这听起来像是满足您需求的完美条件。

    所以,我会尝试以下方法:

    add_action( 'woocommerce_email_before_order_table', 'so_43094965_order_item_names', 10, 4 ); 
    
    function so_43094965_order_item_names( $order, $sent_to_admin, $plain_text, $email ){
        if( $sent_to_admin ){
            add_filter( 'woocommerce_order_item_name', 'filter_woocommerce_order_item_name', 10, 3 );
        }
    }
    

    这会添加您的过滤器,但前提是您在管理员电子邮件中。

    然后:

    add_action( 'woocommerce_email_after_order_table', 'so_43094965_remove_order_item_names', 10, 4 ); 
    
    function so_43094965_remove_order_item_names( $order, $sent_to_admin, $plain_text, $email ){
        remove_filter( 'woocommerce_order_item_name', 'filter_woocommerce_order_item_name', 10, 3 );
    }
    

    这会将其删除,因此它不会出现在其他地方...我不确定是否需要它,但为了完整起见,我将其扔在那里。

    这是未经测试的,因此您的里程可能会有所不同。

    【讨论】:

      猜你喜欢
      • 2016-02-16
      • 2015-03-28
      • 2015-06-16
      • 2013-12-24
      • 1970-01-01
      • 1970-01-01
      • 2013-04-19
      • 2018-10-26
      • 1970-01-01
      相关资源
      最近更新 更多