WooCommerce Integration
Xe Plugin includes sample implementations for extending WooCommerce products both on the backend (Admin) and on the frontend store.
1. Backend Custom Product Fields (src/Admin/Product.php)
Add custom inputs to the standard WooCommerce Product Data metabox:
namespace Xe_Plugin\Frontend; // or Admin
class Product {
public function register(): void {
add_action( 'woocommerce_product_options_general_product_data', [ $this, 'add_general_fields' ] );
add_action( 'woocommerce_process_product_meta', [ $this, 'save_general_fields' ] );
}
public function add_general_fields() {
woocommerce_wp_text_input( [
'id' => '_sample_metabox',
'label' => esc_html__( 'Custom Field', 'xe-plugin' ),
'wrapper_class' => 'show_if_virtual',
] );
}
public function save_general_fields( $post_id ) {
$product = wc_get_product( $post_id );
$value = sanitize_text_field( $_POST['_sample_metabox'] ?? '' );
$product->update_meta_data( '_sample_metabox', $value );
$product->save();
}
}
2. Frontend Product Add-ons & Dynamic Pricing (src/Frontend/Product.php)
The boilerplate illustrates the full lifecycle of custom frontend product add-on fields:
[Single Product Page] -> [Cart Item Data] -> [Cart Totals Calculation] -> [Order Item Meta] -> [Emails]
Complete Lifecycle Hooks:
namespace Xe_Plugin\Frontend;
class Product {
public function register(): void {
// 1. Render custom input above Add-to-Cart
add_action( 'woocommerce_before_add_to_cart_button', [ $this, 'product_addon' ], 9 );
// 2. Validate input on submit
add_filter( 'woocommerce_add_to_cart_validation', [ $this, 'product_addon_validation' ], 10, 3 );
// 3. Store input in cart session data & adjust item price
add_filter( 'woocommerce_add_cart_item_data', [ $this, 'product_addon_cart_item_data' ], 10, 2 );
// 4. Display add-on info in Cart table
add_filter( 'woocommerce_get_item_data', [ $this, 'product_addon_display_cart' ], 10, 2 );
// 5. Persist to order line items during checkout
add_action( 'woocommerce_add_order_item_meta', [ $this, 'product_addon_order_item_meta' ], 10, 2 );
// 6. Display in Order confirmation page
add_filter( 'woocommerce_order_item_product', [ $this, 'product_addon_display_order' ], 10, 2 );
// 7. Include in customer/admin order emails
add_filter( 'woocommerce_email_order_meta_fields', [ $this, 'product_addon_display_emails' ] );
// 8. Recalculate price in cart totals
add_action( 'woocommerce_before_calculate_totals', [ $this, 'before_calculate_totals' ], 10, 1 );
}
}