Skip to content

Instantly share code, notes, and snippets.

@gonzalesc
Created January 23, 2025 18:32
Show Gist options
  • Save gonzalesc/8601a2b30e92999a2551fef00f3e5507 to your computer and use it in GitHub Desktop.
Save gonzalesc/8601a2b30e92999a2551fef00f3e5507 to your computer and use it in GitHub Desktop.
How to add product custom fields in WooCommerce
<?php
/******************
* Product Hooks
******************/
// Print a product custom field
add_action( 'woocommerce_before_add_to_cart_button', 'printProductCustomFields' );
/***************
* Cart Hooks
***************/
// Save custom field to the art - it has 2 parameters
add_filter( 'woocommerce_add_cart_item_data', 'saveCustomFieldToCart' );
// Print the custom field in the cart
add_filter( 'woocommerce_get_item_data', 'printCustomFieldToCart', 10, 2 );
/****************
* Order Hooks
****************/
// Save custom field in the order - it has 4 parameters
add_action( 'woocommerce_checkout_create_order_line_item', 'saveCustomFieldToOrder', 10, 3 );
/**
* Print a product custom field
* @return void
*/
function printProductCustomFields(): void {
// Gift Message
printf( '<div class="container-gift-message">
<label for="gift-message">%s</label>
<textarea id="gift-message" name="gift_message" style="10px 20px 10px 0;"></textarea>
</div>',
\esc_html__( 'Gift message', 'letsgo' )
);
}
/**
* Save custom field to the art
* @param array $cartItemData
* @return array
*/
function saveCustomFieldToCart( array $cartItemData ): array {
// Return early
if ( ! isset( $_POST['gift_message'] ) ) {
return $cartItemData;
}
return array_merge( $cartItemData, [ 'gift_message' => $_POST['gift_message'] ] );
}
/**
* Print custom field in the cart
* @param array $itemData
* @param array $cartItem
* @return array
*/
function printCustomFieldToCart( array $itemData, array $cartItem ): array {
// Return early
if ( empty( $cartItem['gift_message'] ) ) {
return $itemData;
}
$itemData[] = [
'name' => esc_html__( 'Gift Message', 'letsgo' ),
'value' => $cartItem['gift_message']
];
return $itemData;
}
/**
* Print custom field to Order
* @param WC_Order_Item $item
* @param string $cartItemKey
* @param array $cartValues
* @return void
*/
function saveCustomFieldToOrder( WC_Order_Item $item, string $cartItemKey, array $cartValues ): void {
// Return early
if ( empty( $cartValues['gift_message'] ) ) {
return;
}
$item->add_meta_data( esc_html__(' Gift Message', 'letsgo'), $cartValues['gift_message'] );
$item->save_meta_data();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment