更改格式化的地址顺序不再有效

时间:2014-10-29 18:01:41

标签: wordpress woocommerce

在新版本的WooCommerce中似乎有些变化,这个片段用于更改格式化地址中的项目顺序,以便正常工作....

add_filter( 'woocommerce_order_formatted_billing_address' , 'woo_custom_order_formatted_billing_address' );

/**
 * woo_custom_order_formatted_billing_address
 *
 * @access      public
 * @since       1.0 
 * @return      void
*/
function woo_custom_order_formatted_billing_address() {

    $address = array(
        'first_name'    => $this->billing_first_name,
        'last_name'     => $this->billing_last_name,
        'company'       => $this->billing_company,
        'address_1'     => $this->billing_address_1,
        'address_2'     => $this->billing_address_2,
        'city'          => $this->billing_city,
        'state'         => $this->billing_state,
        'postcode'      => $this->billing_postcode,
        'country'       => $this->billing_country
    );

    return $address;

}

但现在它返回以下错误......

致命错误:在

中不在对象上下文中时使用$ this

任何人都可以指出我正确的方向是出现问题还是另一种方法来实现它?

2 个答案:

答案 0 :(得分:1)

我在互联网上看到这个例子,但我不知道它是否有效。首先是因为在'woocommerce_order_formatted_billing_address'过滤器中应用了class-wc-order.php文件,提供了两个参数,$address ARRAY和对当前WC_Order OBJECT的引用。但是您对过滤器函数的定义不提供任何参数。其次,您收到的错误非常准确地描述了问题,伪变量$this可从对象上下文中获得,但您的全局函数不是任何对象的一部分。

足够的技术性,定义应如下所示:

add_filter( 'woocommerce_order_formatted_billing_address' , 'woo_custom_order_formatted_billing_address', 10, 2 );

function woo_custom_order_formatted_billing_address( $address, $wc_order ) {

    // make the changes to $address array here
    // use for example, $wc_order->billing_first_name, instead of $this->billing_first_name

    return $address;
}

答案 1 :(得分:0)

@ Eolis'回答doens对我有用,因为Woocommerce应用了WC()->countries->get_formatted_address( $address ),这个函数会删除添加到add_filter数组的新字段,所以我的解决方案是将字段添加到前一个字段(first_name):

add_filter('woocommerce_order_formatted_billing_address', 'my_order_formatted_billing_address', 10, 2);
function my_order_formatted_billing_address($address, $wc_order) {
    $billing_last_name_2 = get_post_meta( $wc_order->id, '_billing_last_name_2', true );
    $address = array(
        'postcode'      => $wc_order->billing_postcode,
        'last_name'     => $wc_order->billing_last_name,
        //\n force break line
        'first_name'    => $wc_order->billing_first_name . "\n" . $billing_last_name_2,

        'address_1'     => $wc_order->billing_address_1,
        'address_2'     => $wc_order->billing_address_2,
        'city'          => $wc_order->billing_city,
        'state'         => $wc_order->billing_state,

        'country'       => $wc_order->billing_country
    );
    return $address;
}