最近在接触WooCommerce 开发,突然发现国内有关WooCommerce 的中文资料少的可怜,但还好有谷歌。这篇文章意在记录一个问题,在默认的WooCommerce 的结算(checkout)页面上自定义(删除/添加)表单元素。
默认的话,WooCommerce 的结算(checkout)页面上的表单元素(fields)比较繁多,如国家、地址(精确到了省、市、镇)、姓名、邮编、电话、email等等。但在实际项目需求中,可能不想显示那么多的fields;而且从用户体验的角度上,fields应该精简到只需要最重要的——如果是卖虚拟商品的话尤为如此。WooCommerce 中定义这些表单元素(fields)的函数是woocommerce_checkout_fields
,那么我们要自定义,就从这个函数下手,hook 之。
以下根据不同需求写了三个场景。基本上是从官方文档中的《Customizing checkout fields using actions and filters》获取而来。
需求一:删除结算页面上多余的表单元素(fields)
这个多余的表单元素指删除后,只剩下最需要的三个:姓、名、邮箱。这个需求如果单单是做虚拟商品的话就非常有需要。
代码如下:
add_filter( 'woocommerce_checkout_fields' , 'custom_override_checkout_fields' );
function custom_override_checkout_fields( $fields ) {
//unset($fields['order']['order_comments']);
unset( $fields['billing']['billing_country'] );
//unset( $fields['billing']['billing_first_name'] );
//unset( $fields['billing']['billing_last_name'] );
unset( $fields['billing']['billing_company'] );
unset( $fields['billing']['billing_address_1'] );
unset( $fields['billing']['billing_address_2'] );
unset( $fields['billing']['billing_city'] );
unset( $fields['billing']['billing_state'] );
unset( $fields['billing']['billing_postcode'] );
//unset($fields['billing']['billing_email']);
unset( $fields['billing']['billing_phone'] );
return $fields;
}