我正在尝试为woocommerce编写php代码,该代码将检查特定产品是否在购物车中,如果它是真的,那么某些结帐字段将被禁用。我现在所拥有的:
add_action( 'woocommerce_before_checkout_form', 'find_product_in_cart' );
function find_product_in_cart() {
$product_id = 989; //product id which would trigger
$in_cart = false;
foreach( WC()->cart->get_cart() as $cart_item ) {
$product_in_cart = $cart_item['product_id'];
if ( $product_in_cart === $product_id ) $in_cart = true; // checks if the product is in cart
}
if ( $in_cart ) {
add_filter( 'woocommerce_billing_fields', 'woo_filter_state_billing');
function woo_filter_state_billing( $address_fields ) {
//sets fields to not required
$address_fields['billing_state']['required'] = false;
$address_fields['billing_country']['required'] = false;
$address_fields['billing_address_1']['required'] = false;
$address_fields['billing_city']['required'] = false;
$address_fields['billing_postcode']['required'] = false;
$address_fields['billing_phone']['required'] = false;
return $address_fields;
}
add_filter( 'woocommerce_checkout_fields' , 'disabling' );
function disabling($fields){
//hides fields
unset($fields['billing']['billing_company']);
unset($fields['billing']['billing_address_1']);
unset($fields['billing']['billing_city']);
unset($fields['billing']['billing_postcode']);
unset($fields['billing']['billing_phone']);
unset($fields['billing']['billing_country']);
unset($fields['billing']['billing_state']);
return $fields;
}
}
}
因此,问题在于,由于某些原因,即使隐藏了字段,仍然需要保留字段。如果我将其全部剪掉:
add_filter( 'woocommerce_billing_fields', 'woo_filter_state_billing');
function woo_filter_state_billing( $address_fields ) {
//sets fields to not required
$address_fields['billing_state']['required'] = false;
$address_fields['billing_country']['required'] = false;
$address_fields['billing_address_1']['required'] = false;
$address_fields['billing_city']['required'] = false;
$address_fields['billing_postcode']['required'] = false;
$address_fields['billing_phone']['required'] = false;
return $address_fields;
}
并将其粘贴到functions.php中,就可以正常工作,但是它适用于每种产品,这并不好。 那么,我该如何运作呢?
答案 0 :(得分:0)
所以我设法以一种更简洁的方式重做了所有事情,并且一切正常!
add_action( 'woocommerce_before_checkout_form', 'find_product_in_cart' );
所以最后我认为,由于顶部的add_action,未设置的功能无法正常工作:
{{1}}