【问题标题】:With woocommerce_order_get_items filter hook manipulate items name使用 woocommerce_order_get_items 过滤器钩子操作项目名称
【发布时间】:2017-07-17 21:34:55
【问题描述】:

在 WooCommerce 中,如果订单行项目名称带有括号,我试图弄清楚如何删除 ()

这是一些代码:

$order = wc_get_order($order_id)
foreach ( $order->get_items() as $order_item ){
   //...enter code here
}

但我想使用过滤器挂钩,因为我无法访问上面的 foreach 循环。我尝试添加到functions.php,所以当 get_items() 调用时,过滤器将准备数据数组。

代码如下:

add_filter( 'woocommerce_order_get_items', 'filter_woocommerce_order_get_items', 10, 2 ); 
function filter_woocommerce_order_get_items($items, $instance){
    foreach ($items as $item){
        $search = array('å','ä','ö','(', ')');
        $replace = array('a','a','o', '', '');
        $item['name'] = str_replace($search, $replace, $item['name']);
    }

    return $items;
}

所以,TL;DR:
$order->get_items()调用时可以准备数据吗?

谢谢

【问题讨论】:

    标签: php arrays wordpress woocommerce orders


    【解决方案1】:

    您使用正确的过滤器挂钩是正确的方向,但实际上您的自定义挂钩函数不起作用,因为缺少某些东西。

    要使其正常工作,您需要在返回之前用 $items 数组中的新值替换旧值。因此,您的代码中缺少的元素是 $item_id key

    我对你的代码做了一些小改动:

    add_filter( 'woocommerce_order_get_items', 'filter_woocommerce_order_get_items', 10, 2 );
    function filter_woocommerce_order_get_items($items, $instance){
        foreach ($items as $item_id => $item_values){
    
            $search = array('å','ä','ö','(', ')');
            $replace = array('a','a','o', '', '');
    
            $items[$item_id]['name'] = str_replace($search, $replace, $item_values['name']);
        }
        return $items;
    }
    

    代码进入您的活动子主题(或主题)的 function.php 文件或任何插件文件中。

    代码已经过测试并且可以工作。

    【讨论】:

    • 你好,是的,我错过了那部分。我正在检查 /wp-content/plugins/woocommerce/includes/abstracts/abstract-wc-order.php 第 1229 行,但没有注意到 $items[ $item->order_item_id ]['name'] 。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2010-11-14
    • 1970-01-01
    • 1970-01-01
    • 2019-07-09
    • 1970-01-01
    • 2017-04-28
    • 1970-01-01
    • 2019-04-03
    相关资源
    最近更新 更多