问题
Ultimately I am trying to add a field to checkout in woocommerce when a customer has over a certain quantity in their checkout. For this example I am using 500 and just trying to get a message to show at the bottom of checkout.
I have been trying various variations of code and this is what I have so far.
add_action( 'woocommerce_after_checkout_form', 'woocommerce_add_quantity_message', 12 );
function woocommerce_add_quantity_message() {
global $woocommerce;
$total_products = 0;
foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values )
{
$total_products += $values['quantity'];
}
if($total_products >=500 )
{
echo '<div class="card_discount_message"><p>MORE THAN 500 WOAHHHH</p></div>';
}
Any pointers would be greatly appreciated. I have also tried modifying the code found here with no luck woocommerce add fee to cart based on quantity
回答1:
Updated
You can not set a custom checkout field outside of the checkout form.
So this custom fields can only be at the end inside the checkout form, which is after the order notes.
Try the following code that will display a custom checkout field once specific cart item quantity is reached (after order notes):
add_action( 'woocommerce_after_order_notes', 'add_field_based_quantity', 20, 1 );
function add_field_based_quantity( $checkout ) {
if( WC()->cart->get_cart_contents_count() >= 500 ) {
echo '<div id="my_custom_checkout_field"><h2>' . __('My Field') . '</h2>';
woocommerce_form_field( 'my_field_name', array(
'type' => 'text',
'class' => array('my-field-class form-row-wide'),
'label' => __('Fill in this field'),
'placeholder' => __('Enter something'),
), $checkout->get_value( 'my_field_name' ));
echo '</div>';
}
}
Code goes in function.php file of your active child theme (or active theme). Tested and works.
The code is based on Woocommerce official documentation: Adding a custom special checkout field
So you will see in that documentation how to save this custom field in the Order and how you will be able to display it too…
You can add a custom notice at the end if you wish with the following code:
add_action( 'woocommerce_after_checkout_form', 'woocommerce_add_quantity_message', 20 );
function woocommerce_add_quantity_message() {
if( WC()->cart->get_cart_contents_count() >= 500 ) {
wc_print_notice( __("MORE THAN 500 WOAHHHH !", "woocommerce"), 'notice');
}
}
Code goes in function.php file of your active child theme (or active theme). tested and works.
来源:https://stackoverflow.com/questions/51259131/add-a-custom-checkout-field-based-on-cart-items-quantity-in-woocommerce