How to add fields to a cart page in woocommerce?

by edmond_brakus , in category: PHP CMS , 2 months ago

How to add fields to a cart page in woocommerce?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by herminia_bruen , 2 months ago

@edmond_brakus 

To add custom fields to the cart page in WooCommerce, you can use the "woocommerce_cart_fields" filter hook.


Here is an example of how you can add a custom field to the cart page:

  1. Add the following code to your theme's functions.php file:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
// Add custom field to cart page
add_filter( 'woocommerce_cart_fields', 'custom_cart_field' );
function custom_cart_field( $fields ) {
    $fields['custom_field'] = array(
        'label' => __('Custom Field', 'your_text_domain'),
        'placeholder' => _x('Enter custom value', 'placeholder', 'your_text_domain'),
        'required' => true,
        'class' => array( 'form-row-wide' )
    );
    return $fields;
}


  1. Display the custom field on the cart page by adding the following code to the cart template file (typically located in your theme's woocommerce/cart folder):
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
<?php do_action( 'woocommerce_before_cart_table' ); ?>

<form class="woocommerce-cart-form" action="<?php echo esc_url( wc_get_cart_url() ); ?>" method="post">

    <?php do_action( 'woocommerce_before_cart_contents' ); ?>

    <?php
    foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
        $_product = apply_filters( 'woocommerce_cart_item_product', $cart_item['data'], $cart_item, $cart_item_key );
        // Display custom field here
        echo '<input type="text" name="cart[' . $cart_item_key . '][custom_field]" value="' . esc_attr( isset( $cart_item['custom_field'] ) ? $cart_item['custom_field'] : '' ) . '" />';
    }
    ?>

</form>


This code will add a custom field labeled "Custom Field" to the cart page and display it below each cart item. Remember to replace "your_text_domain" with your actual text domain.


You can customize the code further to suit your specific requirements and design preferences.