将自定义woocommerce字段复制到默认字段中

时间:2013-01-13 22:04:13

标签: php wordpress woocommerce

我写了一个woocommerce插件,创建了以下自定义结帐字段:

billing_street_name
billing_house_number
billing_house_number_suffix

shipping_street_name
shipping_house_number
shipping_house_number_suffix

我还将此添加到管理页面,但由于我无法挂钩到get_formatted_billing_address& get_formatted_shipping_address(它们都用于显示writepanel-order_data.php和shop_order.php中的地址)我想将它们复制到默认的billing_address_1& shipping_address_1是这样的:

billing_address_1 = billing_street_name + billing_house_number + billing_house_number_suffix

我尝试使用以下(基本)代码执行此操作:

add_action( 'woocommerce_process_checkout_field_billing_address_1', array( &$this, 'combine_street_number_suffix' ) );

public function combine_street_number_suffix () {
$key = $_POST['billing_street_name'] . ' ' . $_POST['billing_house_number'];

return $key;
}

但这不起作用 - 我认为$ _POST变量根本不会传递?

这是在类-wc-checkout.php中创建钩子的方式:

// Hook to allow modification of value
$this->posted[ $key ] = apply_filters( 'woocommerce_process_checkout_field_' . $key, $this->posted[$key] );

1 个答案:

答案 0 :(得分:1)

使用'woocommerce_checkout_update_order_meta'钩子解决了这个问题:

add_action('woocommerce_checkout_update_order_meta', array( &$this, 'combine_street_number_suffix' ) );

public function combine_street_number_suffix ( $order_id ) {
    // check for suffix
    if ( $_POST['billing_house_number_suffix'] ){
        $billing_house_number = $_POST['billing_house_number'] . '-' . $_POST['billing_house_number_suffix'];
    } else {
        $billing_house_number = $_POST['billing_house_number'];
    }

    // concatenate street & house number & copy to 'billing_address_1'
    $billing_address_1 = $_POST['billing_street_name'] . ' ' . $billing_house_number;
    update_post_meta( $order_id,  '_billing_address_1', $billing_address_1 );

    // check if 'ship to billing address' is checked
    if ( $_POST['shiptobilling'] ) {
        // use billing address
        update_post_meta( $order_id,  '_shipping_address_1', $billing_address_1 );
    } else {
        if ( $_POST['shipping_house_number_suffix'] ){
            $shipping_house_number = $_POST['shipping_house_number'] . '-' . $_POST['shipping_house_number_suffix'];
        } else {
            $shipping_house_number = $_POST['shipping_house_number'];
        }

        // concatenate street & house number & copy to 'shipping_address_1'
        $shipping_address_1 = $_POST['shipping_street_name'] . ' ' . $shipping_house_number;
        update_post_meta( $order_id,  '_shipping_address_1', $shipping_address_1 );         
    }


    return;
}

我不认为这段代码非常优雅(具体来说是后缀检查部分),所以如果有人提出改进它的提示 - 非常欢迎!