Skip to content

Instantly share code, notes, and snippets.

@clifgriffin
Last active March 25, 2022 14:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save clifgriffin/e4666d5fb200514bcd0e68b2a06e8c7b to your computer and use it in GitHub Desktop.
Save clifgriffin/e4666d5fb200514bcd0e68b2a06e8c7b to your computer and use it in GitHub Desktop.
Add a greeting card field to the checkout page after the order notes.
<?php
// Do NOT include the opening php tag.
// Place in your theme's functions.php file
/**
* You can use the following example to add virtually any custom fields
* to the checkout page. To more specifically control the location, use
* our hook guide: https://kb.checkoutwc.com/article/25-actions
*/
/**
* Add the field to the checkout page
*/
add_action( 'cfw_checkout_before_payment_method_terms_checkbox', 'customise_checkout_field' );
function customise_checkout_field() {
woocommerce_form_field(
'greeting_card',
array(
'type' => 'textarea',
'label' => 'Greeting Card',
'placeholder' => 'Greeting Card',
'required' => false,
'class' => array(),
'autofocus' => false,
'priority' => 10,
'columns' => 12,
),
WC()->checkout->get_value( 'customised_field_name' )
);
}
/**
* Update value of field
*/
add_action( 'woocommerce_checkout_update_order_meta', 'customise_checkout_field_update_order_meta' );
function customise_checkout_field_update_order_meta( $order_id ) {
if ( ! empty( $_POST['greeting_card'] ) ) {
update_post_meta( $order_id, 'greeting_card', sanitize_text_field( $_POST['greeting_card'] ) );
}
}
/**
* Display field value on the order edit page
*/
add_action( 'woocommerce_admin_order_data_after_billing_address', 'greeting_card_checkout_field_display_admin_order_meta', 10, 1 );
function greeting_card_checkout_field_display_admin_order_meta($order){
echo '<p><strong>'.__('Greeting Card').':</strong> <br/>' . get_post_meta( $order->get_id(), 'greeting_card', true ) . '</p>';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment