Gift Wrapping Option at Checkout
Adds a "Gift wrap this order" checkbox to the classic checkout for a small fee and flags the order so your packers can spot it.
Opens WPIDE on
Code
$wpide_gift_wrap = array(
'label' => 'Gift wrapping',
'price' => 3.50,
);
$wpide_gift_wrap_chosen = function () {
// phpcs:disable WordPress.Security.NonceVerification -- WooCommerce verifies its checkout requests.
if ( isset( $_POST['post_data'] ) ) {
parse_str( wp_unslash( $_POST['post_data'] ), $posted );
WC()->session->set( 'wpide_gift_wrap', ! empty( $posted['wpide_gift_wrap'] ) );
} elseif ( isset( $_POST['woocommerce-process-checkout-nonce'] ) ) {
WC()->session->set( 'wpide_gift_wrap', ! empty( $_POST['wpide_gift_wrap'] ) );
}
// phpcs:enable
return (bool) WC()->session->get( 'wpide_gift_wrap', false );
};
add_action( 'woocommerce_review_order_before_order_total', function () use ( $wpide_gift_wrap, $wpide_gift_wrap_chosen ) {
printf(
'<tr class="wpide-gift-wrap"><th>%s</th><td><label><input type="checkbox" name="wpide_gift_wrap" value="1" onchange="jQuery(document.body).trigger(\'update_checkout\')" %s> %s</label></td></tr>',
esc_html( $wpide_gift_wrap['label'] ),
checked( $wpide_gift_wrap_chosen(), true, false ),
wp_kses_post( sprintf( 'Gift wrap this order (+%s)', wc_price( $wpide_gift_wrap['price'] ) ) )
);
} );
add_action( 'woocommerce_cart_calculate_fees', function ( $cart ) use ( $wpide_gift_wrap, $wpide_gift_wrap_chosen ) {
if ( ( is_admin() && ! wp_doing_ajax() ) || ! WC()->session || ! $wpide_gift_wrap_chosen() ) {
return;
}
$cart->add_fee( $wpide_gift_wrap['label'], $wpide_gift_wrap['price'], true );
} );
add_action( 'woocommerce_checkout_create_order', function ( $order ) use ( $wpide_gift_wrap_chosen ) {
if ( WC()->session && $wpide_gift_wrap_chosen() ) {
$order->update_meta_data( '_wpide_gift_wrap', 'yes' );
}
} );
add_action( 'woocommerce_admin_order_data_after_order_details', function ( $order ) {
if ( 'yes' === $order->get_meta( '_wpide_gift_wrap' ) ) {
echo '<p class="form-field form-field-wide" style="color:#b32d2e;font-weight:600">' . esc_html( 'Gift wrap this order' ) . '</p>';
}
} );
Notes
Set the price and label at the top; gift-wrapped orders are flagged on the order screen.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.