我在WooCommerce签出中添加了一个自定义字段,如下所示:
function oc_add_checkout_fields( $fields ) {
$fields[\'shipping_sub_area\'] = array(
\'label\' => __( \'Sub Area\' ),
\'type\' => \'select\',
\'class\' => array( \'form-row-wide\', \'update_totals_on_change\' ),
\'priority\' => 68,
\'required\' => true,
\'id\' => \'th_sub_area\',
\'options\' => array(
\'\' =>\'Select\',
\'Clifton\' => \'Clifton1\',
\'DHA\' => \'DHA1\',
),
\'custom_attributes\' => array(),
\'validate\' => array(),
\'default\' => \'\',
);
return $fields;
}
add_filter( \'woocommerce_default_address_fields\', \'oc_add_checkout_fields\' );
更改此字段后,签出表单中的“您的订单”部分会显示预加载程序。我想执行以下操作:如果上述字段中的选定值为Clifton1,则将运费100添加到购物车,否则将运费300添加到购物车,
我尝试了不同的钩子和操作,但无法获得钩子中自定义添加字段的值。例如,我使用了以下过滤器:
function filter_woocommerce_cart_shipping_packages( $array ) {
// make filter magic happen here...
//die(\'I am hre\');
echo \'<pre>\';
print_r($array);
return $array;
};
// add the filter
add_filter( \'woocommerce_cart_shipping_packages\', \'filter_woocommerce_cart_shipping_packages\', 10, 1 );
在中
$array
, 我得到:
[destination] => Array
(
[country] => PK
[state] => TA
[postcode] =>
[city] => fds
[address] => fsdf
[address_1] => fsdf
[address_2] => fsd
)
但我没有得到
shipping_sub_area
或
th_sub_area
.
最合适的回答,由SO网友:Rizwan Zakir 整理而成
首先需要使用ajax在WooCommerce会话变量中设置值。一旦在wc()->会话中设置了值,就可以在WooCommerce挂钩或操作中的任何位置访问它们。
请参见以下代码示例:
/*Ajax Call Back*/
add_action( \'wp_ajax_my_action\', \'my_action_callback\' );
$shipping_charges;
function my_action_callback() {
$shipping_charges = $_POST[\'shipping_charges\'];
WC()->session->set("th_shipping_charges", $shipping_charges );
}
/*Ajax code to get values from the form and post to Wordpress backend*/
add_action( \'wp_footer\', \'my_footer_code\' );
function my_footer_code() {
$html=\'
jQuery("#th_sub_area").change(function(){
var shipping_charges;
var selected_sub_area = jQuery("#th_sub_area").find(":selected").val();
if(selected_sub_area=\'DHA\'){
var shipping_charges= 150;
}
/ In front end of WordPress we have to define ajaxurl /
var ajaxurl = "\'.admin_url(\'admin-ajax.php\').\'";
var data = {
"action": "my_action",
"shipping_charges" : shipping_charges,
};
jQuery.post(ajaxurl, data, function(response) {
jQuery("body").trigger("update_checkout");
});
});
\';
echo $html;
}