WooCommerce Development: The Complete E-commerce Guide
WooCommerce powers over 28% of all online stores, making it the world's most popular e-commerce platform. Its flexibility, extensive ecosystem, and seamless WordPress integration make it the go-to choice for businesses of all sizes. This comprehensive guide covers everything from basic setup to advanced development techniques, helping you build powerful, scalable e-commerce solutions.
Whether you're creating a simple product catalog or a complex multi-vendor marketplace, understanding WooCommerce's architecture and capabilities is crucial for success. We'll explore custom product types, payment integrations, performance optimization, and advanced features that transform WooCommerce from a simple shopping cart into a complete e-commerce platform.
Table of Contents
- WooCommerce Architecture and Setup
- Product Management and Custom Types
- Payment Gateway Development
- Order Management and Fulfillment
- Performance Optimization
- Security and Compliance
- Advanced Features and Integrations
WooCommerce Architecture and Setup
Understanding WooCommerce Core
WooCommerce extends WordPress with comprehensive e-commerce functionality through a well-architected plugin system:
// WooCommerce core architecture overview
class WooCommerce_Architecture {
/**
* Core components initialization
*/
public function __construct() {
// Post types
$this->register_post_types();
// Taxonomies
$this->register_taxonomies();
// Database tables
$this->create_tables();
// Core classes
$this->load_classes();
// Hooks and filters
$this->init_hooks();
}
private function register_post_types() {
// Products
register_post_type('product', [
'labels' => [
'name' => __('Products', 'woocommerce'),
'singular_name' => __('Product', 'woocommerce'),
],
'public' => true,
'capability_type' => 'product',
'map_meta_cap' => true,
'supports' => ['title', 'editor', 'thumbnail', 'excerpt', 'custom-fields'],
'has_archive' => true,
'rewrite' => ['slug' => 'product'],
]);
// Orders (Custom table-based in WC 3.0+)
register_post_type('shop_order', [
'labels' => [
'name' => __('Orders', 'woocommerce'),
'singular_name' => __('Order', 'woocommerce'),
],
'public' => false,
'show_ui' => true,
'capability_type' => 'shop_order',
'map_meta_cap' => true,
'exclude_from_search' => true,
]);
// Coupons
register_post_type('shop_coupon', [
'labels' => [
'name' => __('Coupons', 'woocommerce'),
'singular_name' => __('Coupon', 'woocommerce'),
],
'public' => false,
'show_ui' => true,
'capability_type' => 'shop_coupon',
'map_meta_cap' => true,
]);
}
private function register_taxonomies() {
// Product categories
register_taxonomy('product_cat', ['product'], [
'hierarchical' => true,
'labels' => [
'name' => __('Categories', 'woocommerce'),
'singular_name' => __('Category', 'woocommerce'),
],
'rewrite' => ['slug' => 'product-category'],
]);
// Product tags
register_taxonomy('product_tag', ['product'], [
'hierarchical' => false,
'labels' => [
'name' => __('Tags', 'woocommerce'),
'singular_name' => __('Tag', 'woocommerce'),
],
'rewrite' => ['slug' => 'product-tag'],
]);
// Product attributes (dynamic)
$this->register_attribute_taxonomies();
}
private function create_tables() {
global $wpdb;
$tables = [
"{$wpdb->prefix}woocommerce_sessions",
"{$wpdb->prefix}woocommerce_api_keys",
"{$wpdb->prefix}woocommerce_attribute_taxonomies",
"{$wpdb->prefix}woocommerce_downloadable_product_permissions",
"{$wpdb->prefix}woocommerce_order_items",
"{$wpdb->prefix}woocommerce_order_itemmeta",
"{$wpdb->prefix}woocommerce_tax_rates",
"{$wpdb->prefix}woocommerce_tax_rate_locations",
"{$wpdb->prefix}woocommerce_shipping_zones",
"{$wpdb->prefix}woocommerce_shipping_zone_locations",
"{$wpdb->prefix}woocommerce_shipping_zone_methods",
"{$wpdb->prefix}woocommerce_payment_tokens",
"{$wpdb->prefix}woocommerce_payment_tokenmeta",
];
// HPOS tables (High-Performance Order Storage)
$tables[] = "{$wpdb->prefix}wc_orders";
$tables[] = "{$wpdb->prefix}wc_order_addresses";
$tables[] = "{$wpdb->prefix}wc_order_operational_data";
$tables[] = "{$wpdb->prefix}wc_order_meta";
return $tables;
}
}
Advanced WooCommerce Setup
// Professional WooCommerce setup and configuration
class WooCommerce_Professional_Setup {
/**
* Initialize professional WooCommerce setup
*/
public function __construct() {
add_action('init', [$this, 'configure_woocommerce']);
add_action('woocommerce_init', [$this, 'advanced_configuration']);
add_filter('woocommerce_get_settings_pages', [$this, 'add_custom_settings']);
}
/**
* Configure WooCommerce settings programmatically
*/
public function configure_woocommerce() {
// Enable HPOS (High-Performance Order Storage)
update_option('woocommerce_feature_custom_order_tables_enabled', 'yes');
update_option('woocommerce_custom_orders_table_enabled', 'yes');
// Configure currency and pricing
update_option('woocommerce_currency', 'USD');
update_option('woocommerce_price_decimal_sep', '.');
update_option('woocommerce_price_thousand_sep', ',');
update_option('woocommerce_price_num_decimals', '2');
// Tax configuration
update_option('woocommerce_calc_taxes', 'yes');
update_option('woocommerce_tax_based_on', 'shipping');
update_option('woocommerce_tax_round_at_subtotal', 'yes');
// Shipping configuration
update_option('woocommerce_ship_to_countries', 'all');
update_option('woocommerce_shipping_cost_requires_address', 'yes');
update_option('woocommerce_shipping_debug_mode', 'no');
// Checkout configuration
update_option('woocommerce_enable_guest_checkout', 'yes');
update_option('woocommerce_enable_checkout_login_reminder', 'yes');
update_option('woocommerce_enable_signup_and_login_from_checkout', 'yes');
// Security settings
update_option('woocommerce_force_ssl_checkout', 'yes');
update_option('woocommerce_unforce_ssl_checkout', 'no');
}
/**
* Advanced configuration and optimizations
*/
public function advanced_configuration() {
// Configure image sizes
add_image_size('woocommerce_thumbnail', 300, 300, true);
add_image_size('woocommerce_single', 600, 600, true);
add_image_size('woocommerce_gallery_thumbnail', 100, 100, true);
// Configure product data tabs
add_filter('woocommerce_product_data_tabs', [$this, 'add_custom_product_tabs']);
// Configure checkout fields
add_filter('woocommerce_checkout_fields', [$this, 'customize_checkout_fields']);
// Configure email settings
add_filter('woocommerce_email_classes', [$this, 'add_custom_email_classes']);
// Performance optimizations
$this->configure_performance_settings();
}
/**
* Configure performance settings
*/
private function configure_performance_settings() {
// Limit cart session expiry
add_filter('wc_session_expiring', function() {
return 47 * HOUR_IN_SECONDS;
});
add_filter('wc_session_expiration', function() {
return 48 * HOUR_IN_SECONDS;
});
// Configure AJAX settings
add_filter('woocommerce_ajax_variation_threshold', function() {
return 100; // Limit AJAX variations
});
// Configure database queries
add_filter('woocommerce_product_query_meta_query', [$this, 'optimize_product_queries']);
add_filter('woocommerce_order_query_args', [$this, 'optimize_order_queries']);
// Configure caching
$this->setup_caching_rules();
}
/**
* Setup caching rules for WooCommerce
*/
private function setup_caching_rules() {
// Exclude WooCommerce pages from cache
if (function_exists('wp_cache_add_non_persistent_groups')) {
wp_cache_add_non_persistent_groups(['wc_session_id']);
}
// Define dynamic pages
$dynamic_pages = [
wc_get_page_id('cart'),
wc_get_page_id('checkout'),
wc_get_page_id('myaccount'),
];
// Add cache exclusion rules
foreach ($dynamic_pages as $page_id) {
if ($page_id > 0) {
add_action('wp', function() use ($page_id) {
if (is_page($page_id)) {
nocache_headers();
}
});
}
}
}
}
// Initialize professional setup
new WooCommerce_Professional_Setup();
WooCommerce Database Structure
// Understanding WooCommerce database architecture
class WooCommerce_Database_Structure {
/**
* Document core database relationships
*/
public function get_database_schema() {
global $wpdb;
return [
'products' => [
'table' => $wpdb->posts,
'meta_table' => $wpdb->postmeta,
'relationships' => [
'categories' => $wpdb->term_relationships,
'attributes' => $wpdb->prefix . 'woocommerce_attribute_taxonomies',
'variations' => $wpdb->posts . ' (post_parent relationship)',
],
'key_meta' => [
'_price',
'_regular_price',
'_sale_price',
'_sku',
'_stock',
'_stock_status',
'_visibility',
'_featured',
'_virtual',
'_downloadable',
'_weight',
'_length',
'_width',
'_height',
],
],
'orders' => [
'table' => $wpdb->prefix . 'wc_orders', // HPOS
'legacy_table' => $wpdb->posts,
'meta_table' => $wpdb->prefix . 'wc_order_meta',
'items_table' => $wpdb->prefix . 'woocommerce_order_items',
'itemmeta_table' => $wpdb->prefix . 'woocommerce_order_itemmeta',
'relationships' => [
'customer' => $wpdb->prefix . 'wc_customer_lookup',
'addresses' => $wpdb->prefix . 'wc_order_addresses',
'operational_data' => $wpdb->prefix . 'wc_order_operational_data',
],
],
'customers' => [
'table' => $wpdb->users,
'meta_table' => $wpdb->usermeta,
'lookup_table' => $wpdb->prefix . 'wc_customer_lookup',
'key_meta' => [
'billing_first_name',
'billing_last_name',
'billing_company',
'billing_address_1',
'billing_address_2',
'billing_city',
'billing_state',
'billing_postcode',
'billing_country',
'billing_email',
'billing_phone',
'shipping_first_name',
'shipping_last_name',
'shipping_company',
'shipping_address_1',
'shipping_address_2',
'shipping_city',
'shipping_state',
'shipping_postcode',
'shipping_country',
],
],
'analytics' => [
'orders_stats' => $wpdb->prefix . 'wc_order_stats',
'products_lookup' => $wpdb->prefix . 'wc_product_lookup',
'customers_lookup' => $wpdb->prefix . 'wc_customer_lookup',
'categories_lookup' => $wpdb->prefix . 'wc_category_lookup',
],
];
}
/**
* Optimize database queries
*/
public function optimize_database() {
global $wpdb;
// Add indexes for better performance
$indexes = [
[
'table' => $wpdb->postmeta,
'name' => 'idx_meta_key_value',
'columns' => 'meta_key(191), meta_value(100)',
],
[
'table' => $wpdb->prefix . 'woocommerce_order_items',
'name' => 'idx_order_item_type',
'columns' => 'order_id, order_item_type',
],
[
'table' => $wpdb->prefix . 'wc_order_stats',
'name' => 'idx_status_date',
'columns' => 'status(191), date_created',
],
];
foreach ($indexes as $index) {
$this->create_index($index['table'], $index['name'], $index['columns']);
}
}
/**
* Create database index if not exists
*/
private function create_index($table, $index_name, $columns) {
global $wpdb;
$index_exists = $wpdb->get_var($wpdb->prepare(
"SELECT COUNT(1) FROM INFORMATION_SCHEMA.STATISTICS
WHERE table_schema = %s
AND table_name = %s
AND index_name = %s",
DB_NAME,
$table,
$index_name
));
if (!$index_exists) {
$wpdb->query("CREATE INDEX $index_name ON $table ($columns)");
}
}
}
Product Management and Custom Types
Creating Custom Product Types
// Advanced custom product type implementation
class WC_Product_Custom_Type extends WC_Product {
/**
* Product type name
*/
protected $product_type = 'custom_type';
/**
* Constructor
*/
public function __construct($product = 0) {
parent::__construct($product);
}
/**
* Get product type
*/
public function get_type() {
return 'custom_type';
}
/**
* Product type specific functionality
*/
public function add_to_cart_url() {
$url = $this->is_purchasable() && $this->is_in_stock()
? remove_query_arg('added-to-cart', add_query_arg('add-to-cart', $this->get_id()))
: get_permalink($this->get_id());
return apply_filters('woocommerce_product_add_to_cart_url', $url, $this);
}
/**
* Get add to cart button text
*/
public function add_to_cart_text() {
$text = $this->is_purchasable() && $this->is_in_stock()
? __('Add to cart', 'woocommerce')
: __('Read more', 'woocommerce');
return apply_filters('woocommerce_product_add_to_cart_text', $text, $this);
}
/**
* Check if product can be purchased
*/
public function is_purchasable() {
return apply_filters('woocommerce_is_purchasable', true, $this);
}
/**
* Custom validation for this product type
*/
public function validate_add_to_cart($quantity = 1) {
$validation = true;
// Custom validation logic
if ($this->get_meta('_requires_approval') === 'yes') {
if (!current_user_can('purchase_restricted_products')) {
wc_add_notice(__('This product requires approval to purchase.', 'woocommerce'), 'error');
$validation = false;
}
}
// Check custom limits
$max_quantity = $this->get_meta('_max_quantity_per_order');
if ($max_quantity && $quantity > $max_quantity) {
wc_add_notice(
sprintf(
__('Maximum quantity per order is %d.', 'woocommerce'),
$max_quantity
),
'error'
);
$validation = false;
}
return apply_filters('woocommerce_add_to_cart_validation', $validation, $this->get_id(), $quantity);
}
}
// Register custom product type
class WC_Custom_Product_Type_Manager {
public function __construct() {
add_filter('product_type_selector', [$this, 'add_product_type']);
add_filter('woocommerce_product_class', [$this, 'load_product_class'], 10, 2);
add_action('admin_footer', [$this, 'add_product_type_options']);
add_action('woocommerce_process_product_meta_custom_type', [$this, 'save_product_data']);
// Add custom tabs
add_filter('woocommerce_product_data_tabs', [$this, 'add_product_tabs']);
add_action('woocommerce_product_data_panels', [$this, 'add_product_panels']);
}
/**
* Add custom product type to selector
*/
public function add_product_type($types) {
$types['custom_type'] = __('Custom Product Type', 'woocommerce');
return $types;
}
/**
* Load custom product class
*/
public function load_product_class($classname, $product_type) {
if ($product_type === 'custom_type') {
$classname = 'WC_Product_Custom_Type';
}
return $classname;
}
/**
* Add custom product options
*/
public function add_product_type_options() {
if ('product' !== get_post_type()) {
return;
}
?>
<script type='text/javascript'>
jQuery(document).ready(function($) {
// Add custom options
$('.options_group.pricing').addClass('show_if_custom_type');
// Custom type specific options
jQuery('.product_data_tabs .general_tab').addClass('show_if_custom_type');
jQuery('#general_product_data .pricing').addClass('show_if_custom_type');
// Show/hide on load
if ($('#product-type').val() === 'custom_type') {
$('.show_if_custom_type').show();
}
// Show/hide on change
$('#product-type').on('change', function() {
if ($(this).val() === 'custom_type') {
$('.show_if_custom_type').show();
}
});
});
</script>
<?php
}
/**
* Add custom product data tabs
*/
public function add_product_tabs($tabs) {
$tabs['custom_options'] = [
'label' => __('Custom Options', 'woocommerce'),
'target' => 'custom_options_data',
'class' => ['show_if_custom_type'],
'priority' => 21,
];
return $tabs;
}
/**
* Add custom product data panels
*/
public function add_product_panels() {
global $post;
?>
<div id='custom_options_data' class='panel woocommerce_options_panel'>
<div class='options_group'>
<?php
woocommerce_wp_checkbox([
'id' => '_requires_approval',
'label' => __('Requires Approval', 'woocommerce'),
'description' => __('Check this box if the product requires approval before purchase.', 'woocommerce'),
]);
woocommerce_wp_text_input([
'id' => '_max_quantity_per_order',
'label' => __('Max Quantity per Order', 'woocommerce'),
'type' => 'number',
'custom_attributes' => [
'step' => '1',
'min' => '1',
],
]);
woocommerce_wp_textarea_input([
'id' => '_custom_product_message',
'label' => __('Custom Product Message', 'woocommerce'),
'placeholder' => __('Enter a custom message for this product type', 'woocommerce'),
'desc_tip' => true,
'description' => __('This message will be displayed on the product page.', 'woocommerce'),
]);
?>
</div>
</div>
<?php
}
/**
* Save custom product data
*/
public function save_product_data($post_id) {
$requires_approval = isset($_POST['_requires_approval']) ? 'yes' : 'no';
update_post_meta($post_id, '_requires_approval', $requires_approval);
if (isset($_POST['_max_quantity_per_order'])) {
update_post_meta($post_id, '_max_quantity_per_order', absint($_POST['_max_quantity_per_order']));
}
if (isset($_POST['_custom_product_message'])) {
update_post_meta($post_id, '_custom_product_message', sanitize_textarea_field($_POST['_custom_product_message']));
}
}
}
// Initialize custom product type
new WC_Custom_Product_Type_Manager();
Advanced Product Variations
// Advanced product variation management
class WC_Advanced_Variations_Manager {
/**
* Initialize advanced variations
*/
public function __construct() {
// Bulk variation creation
add_action('woocommerce_variable_product_bulk_actions', [$this, 'add_bulk_actions']);
add_action('woocommerce_bulk_edit_variations', [$this, 'bulk_edit_variations'], 10, 4);
// Custom variation fields
add_action('woocommerce_product_after_variable_attributes', [$this, 'add_custom_variation_fields'], 10, 3);
add_action('woocommerce_save_product_variation', [$this, 'save_custom_variation_fields'], 10, 2);
// Variation display customization
add_filter('woocommerce_available_variation', [$this, 'modify_available_variation'], 10, 3);
// AJAX handlers
add_action('wp_ajax_create_all_variations', [$this, 'ajax_create_all_variations']);
}
/**
* Add bulk variation actions
*/
public function add_bulk_actions() {
?>
<option value="create_all_variations"><?php esc_html_e('Create all variations', 'woocommerce'); ?></option>
<option value="set_regular_price_increase"><?php esc_html_e('Increase regular price by percentage', 'woocommerce'); ?></option>
<option value="set_sale_price_decrease"><?php esc_html_e('Decrease sale price by percentage', 'woocommerce'); ?></option>
<?php
}
/**
* Handle bulk edit variations
*/
public function bulk_edit_variations($bulk_action, $data, $product_id, $variations) {
switch ($bulk_action) {
case 'create_all_variations':
$this->create_all_possible_variations($product_id);
break;
case 'set_regular_price_increase':
if (isset($data['value'])) {
$this->adjust_variation_prices($variations, 'regular', $data['value'], 'increase');
}
break;
case 'set_sale_price_decrease':
if (isset($data['value'])) {
$this->adjust_variation_prices($variations, 'sale', $data['value'], 'decrease');
}
break;
}
}
/**
* Create all possible variations
*/
private function create_all_possible_variations($product_id) {
$product = wc_get_product($product_id);
if (!$product || !$product->is_type('variable')) {
return false;
}
$attributes = $product->get_variation_attributes();
$possible_variations = $this->generate_variation_combinations($attributes);
$existing_variations = $product->get_children();
foreach ($possible_variations as $variation_attributes) {
// Check if variation already exists
if ($this->variation_exists($product_id, $variation_attributes, $existing_variations)) {
continue;
}
// Create new variation
$variation = new WC_Product_Variation();
$variation->set_parent_id($product_id);
$variation->set_attributes($variation_attributes);
// Set default data
$variation->set_regular_price($product->get_regular_price());
$variation->set_manage_stock(false);
$variation->set_status('publish');
// Save variation
$variation->save();
}
// Clear caches
WC_Cache_Helper::get_transient_version('product', true);
}
/**
* Generate all possible variation combinations
*/
private function generate_variation_combinations($attributes) {
$combinations = [[]];
foreach ($attributes as $attribute => $values) {
$new_combinations = [];
foreach ($combinations as $combination) {
foreach ($values as $value) {
$new_combination = $combination;
$new_combination[$attribute] = $value;
$new_combinations[] = $new_combination;
}
}
$combinations = $new_combinations;
}
return $combinations;
}
/**
* Check if variation exists
*/
private function variation_exists($product_id, $attributes, $existing_variations) {
foreach ($existing_variations as $variation_id) {
$variation = wc_get_product($variation_id);
if (!$variation) {
continue;
}
$variation_attributes = $variation->get_variation_attributes();
if ($this->attributes_match($attributes, $variation_attributes)) {
return true;
}
}
return false;
}
/**
* Add custom variation fields
*/
public function add_custom_variation_fields($loop, $variation_data, $variation) {
$variation_object = wc_get_product($variation->ID);
?>
<div class="custom-variation-fields">
<p class="form-row form-row-full">
<label><?php esc_html_e('Delivery Time (days)', 'woocommerce'); ?></label>
<input type="number"
name="variable_delivery_time[<?php echo esc_attr($loop); ?>]"
value="<?php echo esc_attr($variation_object->get_meta('_delivery_time')); ?>"
placeholder="<?php esc_attr_e('e.g., 3-5', 'woocommerce'); ?>" />
</p>
<p class="form-row form-row-full">
<label><?php esc_html_e('Minimum Order Quantity', 'woocommerce'); ?></label>
<input type="number"
name="variable_min_quantity[<?php echo esc_attr($loop); ?>]"
value="<?php echo esc_attr($variation_object->get_meta('_min_quantity')); ?>"
min="1"
step="1" />
</p>
<p class="form-row form-row-full">
<label>
<input type="checkbox"
name="variable_is_preorder[<?php echo esc_attr($loop); ?>]"
value="yes"
<?php checked($variation_object->get_meta('_is_preorder'), 'yes'); ?> />
<?php esc_html_e('This is a pre-order product', 'woocommerce'); ?>
</label>
</p>
</div>
<?php
}
/**
* Save custom variation fields
*/
public function save_custom_variation_fields($variation_id, $loop) {
if (isset($_POST['variable_delivery_time'][$loop])) {
update_post_meta($variation_id, '_delivery_time', sanitize_text_field($_POST['variable_delivery_time'][$loop]));
}
if (isset($_POST['variable_min_quantity'][$loop])) {
update_post_meta($variation_id, '_min_quantity', absint($_POST['variable_min_quantity'][$loop]));
}
$is_preorder = isset($_POST['variable_is_preorder'][$loop]) ? 'yes' : 'no';
update_post_meta($variation_id, '_is_preorder', $is_preorder);
}
/**
* Modify available variation data
*/
public function modify_available_variation($data, $product, $variation) {
$data['delivery_time'] = $variation->get_meta('_delivery_time');
$data['min_quantity'] = $variation->get_meta('_min_quantity') ?: 1;
$data['is_preorder'] = $variation->get_meta('_is_preorder') === 'yes';
// Add custom price display
if ($data['is_preorder']) {
$data['price_html'] = '<span class="preorder-price">' . $data['price_html'] . '</span>';
$data['availability_html'] .= '<p class="preorder-notice">' . __('This is a pre-order item', 'woocommerce') . '</p>';
}
return $data;
}
}
// Initialize advanced variations
new WC_Advanced_Variations_Manager();
Product Data Import/Export
// Advanced product import/export functionality
class WC_Advanced_Product_Importer {
/**
* Initialize importer
*/
public function __construct() {
add_filter('woocommerce_csv_product_import_mapping_options', [$this, 'add_custom_import_columns']);
add_filter('woocommerce_csv_product_import_mapping_default_columns', [$this, 'add_column_mappings']);
add_filter('woocommerce_product_importer_parsed_data', [$this, 'parse_custom_data'], 10, 2);
add_filter('woocommerce_product_import_inserted_product_object', [$this, 'process_custom_data'], 10, 2);
// Export functionality
add_filter('woocommerce_product_export_column_names', [$this, 'add_export_columns']);
add_filter('woocommerce_product_export_product_default_columns', [$this, 'add_export_column_mappings']);
add_filter('woocommerce_product_export_product_column_custom_field', [$this, 'export_custom_field'], 10, 3);
}
/**
* Add custom import columns
*/
public function add_custom_import_columns($columns) {
$columns['supplier_sku'] = __('Supplier SKU', 'woocommerce');
$columns['warehouse_location'] = __('Warehouse Location', 'woocommerce');
$columns['reorder_level'] = __('Reorder Level', 'woocommerce');
$columns['lead_time'] = __('Lead Time (days)', 'woocommerce');
$columns['country_of_origin'] = __('Country of Origin', 'woocommerce');
$columns['hs_code'] = __('HS Code', 'woocommerce');
return $columns;
}
/**
* Process imported custom data
*/
public function process_custom_data($product, $data) {
// Process supplier information
if (!empty($data['supplier_sku'])) {
$product->update_meta_data('_supplier_sku', sanitize_text_field($data['supplier_sku']));
}
if (!empty($data['warehouse_location'])) {
$product->update_meta_data('_warehouse_location', sanitize_text_field($data['warehouse_location']));
}
// Process inventory management
if (!empty($data['reorder_level'])) {
$product->update_meta_data('_reorder_level', absint($data['reorder_level']));
// Check if automatic reorder needed
if ($product->get_stock_quantity() <= absint($data['reorder_level'])) {
$this->trigger_reorder_notification($product);
}
}
if (!empty($data['lead_time'])) {
$product->update_meta_data('_lead_time', absint($data['lead_time']));
}
// Process shipping information
if (!empty($data['country_of_origin'])) {
$product->update_meta_data('_country_of_origin', sanitize_text_field($data['country_of_origin']));
}
if (!empty($data['hs_code'])) {
$product->update_meta_data('_hs_code', sanitize_text_field($data['hs_code']));
}
return $product;
}
/**
* Trigger reorder notification
*/
private function trigger_reorder_notification($product) {
$mailer = WC()->mailer();
$recipient = get_option('woocommerce_stock_email_recipient', get_option('admin_email'));
$subject = sprintf(
__('Reorder needed for %s', 'woocommerce'),
$product->get_name()
);
$message = sprintf(
__('The stock level for %s (SKU: %s) has fallen below the reorder level.', 'woocommerce'),
$product->get_name(),
$product->get_sku()
);
$message .= "\n\n" . sprintf(
__('Current Stock: %d', 'woocommerce'),
$product->get_stock_quantity()
);
$message .= "\n" . sprintf(
__('Reorder Level: %d', 'woocommerce'),
$product->get_meta('_reorder_level')
);
$mailer->send($recipient, $subject, $message);
}
}
// Initialize importer
new WC_Advanced_Product_Importer();
```## Payment Gateway Development {#payment-gateways}
### Creating Custom Payment Gateways
```php
// Custom payment gateway implementation
class WC_Gateway_Custom extends WC_Payment_Gateway {
/**
* Constructor
*/
public function __construct() {
$this->id = 'custom_gateway';
$this->icon = apply_filters('woocommerce_custom_gateway_icon', '');
$this->has_fields = true;
$this->method_title = __('Custom Payment Gateway', 'woocommerce');
$this->method_description = __('Accept payments through custom payment gateway', 'woocommerce');
// Load settings
$this->init_form_fields();
$this->init_settings();
// Define user settings
$this->title = $this->get_option('title');
$this->description = $this->get_option('description');
$this->enabled = $this->get_option('enabled');
$this->testmode = 'yes' === $this->get_option('testmode');
$this->api_key = $this->testmode ? $this->get_option('test_api_key') : $this->get_option('live_api_key');
$this->api_secret = $this->testmode ? $this->get_option('test_api_secret') : $this->get_option('live_api_secret');
// Hooks
add_action('woocommerce_update_options_payment_gateways_' . $this->id, [$this, 'process_admin_options']);
add_action('woocommerce_receipt_' . $this->id, [$this, 'receipt_page']);
add_action('woocommerce_api_wc_gateway_custom', [$this, 'webhook_handler']);
// Enqueue scripts
add_action('wp_enqueue_scripts', [$this, 'payment_scripts']);
}
/**
* Initialize gateway settings form fields
*/
public function init_form_fields() {
$this->form_fields = [
'enabled' => [
'title' => __('Enable/Disable', 'woocommerce'),
'type' => 'checkbox',
'label' => __('Enable Custom Payment Gateway', 'woocommerce'),
'default' => 'yes',
],
'title' => [
'title' => __('Title', 'woocommerce'),
'type' => 'text',
'description' => __('This controls the title which the user sees during checkout.', 'woocommerce'),
'default' => __('Custom Payment', 'woocommerce'),
'desc_tip' => true,
],
'description' => [
'title' => __('Description', 'woocommerce'),
'type' => 'textarea',
'description' => __('Payment method description that the customer will see on your checkout.', 'woocommerce'),
'default' => __('Pay securely using our custom payment gateway.', 'woocommerce'),
],
'testmode' => [
'title' => __('Test mode', 'woocommerce'),
'type' => 'checkbox',
'label' => __('Enable Test Mode', 'woocommerce'),
'default' => 'yes',
'description' => __('Place the payment gateway in test mode using test API keys.', 'woocommerce'),
],
'test_api_key' => [
'title' => __('Test API Key', 'woocommerce'),
'type' => 'text',
],
'test_api_secret' => [
'title' => __('Test API Secret', 'woocommerce'),
'type' => 'password',
],
'live_api_key' => [
'title' => __('Live API Key', 'woocommerce'),
'type' => 'text',
],
'live_api_secret' => [
'title' => __('Live API Secret', 'woocommerce'),
'type' => 'password',
],
'webhook_secret' => [
'title' => __('Webhook Secret', 'woocommerce'),
'type' => 'password',
'description' => __('Enter the webhook secret key provided by the payment gateway.', 'woocommerce'),
],
];
}
/**
* Payment form on checkout page
*/
public function payment_fields() {
if ($this->description) {
echo wpautop(wp_kses_post($this->description));
}
if ($this->testmode) {
echo '<p>' . __('TEST MODE ENABLED. Use test card numbers.', 'woocommerce') . '</p>';
}
?>
<fieldset id="wc-<?php echo esc_attr($this->id); ?>-cc-form" class="wc-credit-card-form wc-payment-form">
<?php do_action('woocommerce_credit_card_form_start', $this->id); ?>
<p class="form-row form-row-wide">
<label for="<?php echo esc_attr($this->id); ?>-card-number">
<?php esc_html_e('Card Number', 'woocommerce'); ?> <span class="required">*</span>
</label>
<input id="<?php echo esc_attr($this->id); ?>-card-number"
class="input-text wc-credit-card-form-card-number"
inputmode="numeric"
autocomplete="cc-number"
autocorrect="no"
autocapitalize="no"
spellcheck="no"
type="tel"
placeholder="•••• •••• •••• ••••" />
</p>
<p class="form-row form-row-first">
<label for="<?php echo esc_attr($this->id); ?>-card-expiry">
<?php esc_html_e('Expiry (MM/YY)', 'woocommerce'); ?> <span class="required">*</span>
</label>
<input id="<?php echo esc_attr($this->id); ?>-card-expiry"
class="input-text wc-credit-card-form-card-expiry"
inputmode="numeric"
autocomplete="cc-exp"
autocorrect="no"
autocapitalize="no"
spellcheck="no"
type="tel"
placeholder="<?php esc_attr_e('MM / YY', 'woocommerce'); ?>" />
</p>
<p class="form-row form-row-last">
<label for="<?php echo esc_attr($this->id); ?>-card-cvc">
<?php esc_html_e('Card Code', 'woocommerce'); ?> <span class="required">*</span>
</label>
<input id="<?php echo esc_attr($this->id); ?>-card-cvc"
class="input-text wc-credit-card-form-card-cvc"
inputmode="numeric"
autocomplete="off"
autocorrect="no"
autocapitalize="no"
spellcheck="no"
type="tel"
maxlength="4"
placeholder="<?php esc_attr_e('CVC', 'woocommerce'); ?>" />
</p>
<?php do_action('woocommerce_credit_card_form_end', $this->id); ?>
<div class="clear"></div>
</fieldset>
<?php
}
/**
* Process the payment
*/
public function process_payment($order_id) {
$order = wc_get_order($order_id);
try {
// Validate payment fields
$this->validate_fields();
// Create payment intent
$payment_intent = $this->create_payment_intent($order);
if ($payment_intent['status'] === 'requires_action') {
// 3D Secure or additional authentication required
return [
'result' => 'success',
'redirect' => $order->get_checkout_payment_url(true),
'payment_intent' => $payment_intent['client_secret'],
];
} elseif ($payment_intent['status'] === 'succeeded') {
// Payment successful
$order->payment_complete($payment_intent['id']);
$order->add_order_note(
sprintf(
__('Payment completed via %s (Transaction ID: %s)', 'woocommerce'),
$this->method_title,
$payment_intent['id']
)
);
// Clear cart
WC()->cart->empty_cart();
return [
'result' => 'success',
'redirect' => $this->get_return_url($order),
];
} else {
throw new Exception(__('Payment failed. Please try again.', 'woocommerce'));
}
} catch (Exception $e) {
wc_add_notice($e->getMessage(), 'error');
return [
'result' => 'fail',
'redirect' => '',
];
}
}
/**
* Create payment intent
*/
private function create_payment_intent($order) {
$endpoint = $this->testmode
? 'https://api.sandbox.payment-gateway.com/v1/payment-intents'
: 'https://api.payment-gateway.com/v1/payment-intents';
$request_data = [
'amount' => $order->get_total() * 100, // Convert to cents
'currency' => strtolower($order->get_currency()),
'description' => sprintf(
__('Order %s from %s', 'woocommerce'),
$order->get_order_number(),
get_bloginfo('name')
),
'metadata' => [
'order_id' => $order->get_id(),
'order_key' => $order->get_order_key(),
'customer_email' => $order->get_billing_email(),
],
'capture_method' => 'automatic',
'confirm' => true,
'payment_method_data' => [
'type' => 'card',
'card' => [
'number' => $this->get_post_data('custom_gateway-card-number'),
'exp_month' => $this->get_card_expiry_month(),
'exp_year' => $this->get_card_expiry_year(),
'cvc' => $this->get_post_data('custom_gateway-card-cvc'),
],
'billing_details' => [
'name' => $order->get_formatted_billing_full_name(),
'email' => $order->get_billing_email(),
'phone' => $order->get_billing_phone(),
'address' => [
'line1' => $order->get_billing_address_1(),
'line2' => $order->get_billing_address_2(),
'city' => $order->get_billing_city(),
'state' => $order->get_billing_state(),
'postal_code' => $order->get_billing_postcode(),
'country' => $order->get_billing_country(),
],
],
],
];
$response = wp_remote_post($endpoint, [
'method' => 'POST',
'headers' => [
'Authorization' => 'Bearer ' . $this->api_key,
'Content-Type' => 'application/json',
],
'body' => wp_json_encode($request_data),
'timeout' => 45,
]);
if (is_wp_error($response)) {
throw new Exception(__('Connection error. Please try again.', 'woocommerce'));
}
$response_body = json_decode(wp_remote_retrieve_body($response), true);
if (empty($response_body['id'])) {
$error_message = isset($response_body['error']['message'])
? $response_body['error']['message']
: __('An error occurred processing your payment.', 'woocommerce');
throw new Exception($error_message);
}
return $response_body;
}
/**
* Webhook handler
*/
public function webhook_handler() {
$payload = file_get_contents('php://input');
$sig_header = $_SERVER['HTTP_WEBHOOK_SIGNATURE'] ?? '';
try {
$event = $this->verify_webhook_signature($payload, $sig_header);
switch ($event['type']) {
case 'payment_intent.succeeded':
$this->handle_payment_success($event['data']['object']);
break;
case 'payment_intent.payment_failed':
$this->handle_payment_failure($event['data']['object']);
break;
case 'charge.dispute.created':
$this->handle_dispute($event['data']['object']);
break;
}
status_header(200);
exit;
} catch (Exception $e) {
status_header(400);
exit($e->getMessage());
}
}
/**
* Verify webhook signature
*/
private function verify_webhook_signature($payload, $sig_header) {
$webhook_secret = $this->get_option('webhook_secret');
if (empty($webhook_secret)) {
throw new Exception('Webhook secret not configured');
}
$expected_sig = hash_hmac('sha256', $payload, $webhook_secret);
if (!hash_equals($expected_sig, $sig_header)) {
throw new Exception('Invalid signature');
}
return json_decode($payload, true);
}
}
// Register gateway
add_filter('woocommerce_payment_gateways', function($gateways) {
$gateways[] = 'WC_Gateway_Custom';
return $gateways;
});
Payment Gateway Security
// Advanced payment security implementation
class WC_Payment_Security_Manager {
/**
* Initialize security features
*/
public function __construct() {
// PCI compliance
add_action('wp_enqueue_scripts', [$this, 'enqueue_security_scripts']);
add_filter('woocommerce_checkout_fields', [$this, 'add_security_fields']);
// Fraud detection
add_action('woocommerce_checkout_process', [$this, 'fraud_detection']);
add_filter('woocommerce_payment_complete_order_status', [$this, 'hold_suspicious_orders'], 10, 3);
// Tokenization
add_action('woocommerce_payment_token_set_default', [$this, 'secure_token_storage']);
// Rate limiting
add_action('woocommerce_before_checkout_process', [$this, 'rate_limit_checkout']);
}
/**
* Implement fraud detection
*/
public function fraud_detection() {
$fraud_score = 0;
$fraud_reasons = [];
// Check IP reputation
$ip_score = $this->check_ip_reputation(WC_Geolocation::get_ip_address());
if ($ip_score > 50) {
$fraud_score += $ip_score;
$fraud_reasons[] = 'Suspicious IP address';
}
// Check email domain
$email = $_POST['billing_email'] ?? '';
if ($this->is_disposable_email($email)) {
$fraud_score += 30;
$fraud_reasons[] = 'Disposable email address';
}
// Check velocity (multiple orders in short time)
$velocity_score = $this->check_order_velocity($email);
if ($velocity_score > 0) {
$fraud_score += $velocity_score;
$fraud_reasons[] = 'High order velocity';
}
// Check address verification
if (!$this->verify_address($_POST)) {
$fraud_score += 20;
$fraud_reasons[] = 'Address verification failed';
}
// Device fingerprinting
$device_score = $this->check_device_fingerprint();
if ($device_score > 0) {
$fraud_score += $device_score;
$fraud_reasons[] = 'Suspicious device';
}
// Store fraud score for payment gateway
WC()->session->set('fraud_score', $fraud_score);
WC()->session->set('fraud_reasons', $fraud_reasons);
// Block high-risk transactions
if ($fraud_score >= 80) {
wc_add_notice(
__('Your transaction has been flagged for security review. Please contact support.', 'woocommerce'),
'error'
);
// Log suspicious activity
$this->log_suspicious_activity([
'ip' => WC_Geolocation::get_ip_address(),
'email' => $email,
'score' => $fraud_score,
'reasons' => $fraud_reasons,
]);
}
}
/**
* Check IP reputation
*/
private function check_ip_reputation($ip) {
// Check against known VPN/Proxy lists
$vpn_check = $this->is_vpn_proxy($ip);
if ($vpn_check) {
return 40;
}
// Check against blacklists
$blacklisted = $this->check_ip_blacklists($ip);
if ($blacklisted) {
return 60;
}
// Check geographic anomalies
$geo_score = $this->check_geographic_anomalies($ip);
return $geo_score;
}
/**
* Implement 3D Secure
*/
public function implement_3d_secure($order, $payment_method) {
$amount = $order->get_total();
// Always require 3D Secure for high-value transactions
if ($amount > 500) {
return [
'required' => true,
'reason' => 'high_value',
];
}
// Check fraud score
$fraud_score = WC()->session->get('fraud_score', 0);
if ($fraud_score > 50) {
return [
'required' => true,
'reason' => 'fraud_risk',
];
}
// Check customer history
$customer = $order->get_customer_id();
if ($customer && $this->is_trusted_customer($customer)) {
return [
'required' => false,
'reason' => 'trusted_customer',
];
}
// Default to requiring 3D Secure
return [
'required' => true,
'reason' => 'default_policy',
];
}
}
// Initialize security manager
new WC_Payment_Security_Manager();
Order Management and Fulfillment
Advanced Order Management System
// Comprehensive order management system
class WC_Advanced_Order_Manager {
/**
* Initialize order management features
*/
public function __construct() {
// Custom order statuses
add_action('init', [$this, 'register_custom_order_statuses']);
add_filter('wc_order_statuses', [$this, 'add_custom_order_statuses']);
// Order actions
add_filter('woocommerce_order_actions', [$this, 'add_custom_order_actions'], 10, 2);
add_action('woocommerce_order_action_send_to_fulfillment', [$this, 'handle_send_to_fulfillment']);
// Bulk actions
add_filter('bulk_actions-edit-shop_order', [$this, 'add_bulk_actions']);
add_filter('handle_bulk_actions-edit-shop_order', [$this, 'handle_bulk_actions'], 10, 3);
// Order tracking
add_action('woocommerce_order_status_changed', [$this, 'track_order_status_change'], 10, 4);
// Automated workflows
add_action('woocommerce_order_status_processing', [$this, 'automate_order_processing']);
}
/**
* Register custom order statuses
*/
public function register_custom_order_statuses() {
register_post_status('wc-awaiting-shipment', [
'label' => __('Awaiting Shipment', 'woocommerce'),
'public' => true,
'show_in_admin_status_list' => true,
'show_in_admin_all_list' => true,
'exclude_from_search' => false,
'label_count' => _n_noop(
'Awaiting Shipment <span class="count">(%s)</span>',
'Awaiting Shipment <span class="count">(%s)</span>',
'woocommerce'
),
]);
register_post_status('wc-in-fulfillment', [
'label' => __('In Fulfillment', 'woocommerce'),
'public' => true,
'show_in_admin_status_list' => true,
'show_in_admin_all_list' => true,
'exclude_from_search' => false,
'label_count' => _n_noop(
'In Fulfillment <span class="count">(%s)</span>',
'In Fulfillment <span class="count">(%s)</span>',
'woocommerce'
),
]);
register_post_status('wc-quality-check', [
'label' => __('Quality Check', 'woocommerce'),
'public' => true,
'show_in_admin_status_list' => true,
'show_in_admin_all_list' => true,
'exclude_from_search' => false,
'label_count' => _n_noop(
'Quality Check <span class="count">(%s)</span>',
'Quality Check <span class="count">(%s)</span>',
'woocommerce'
),
]);
}
/**
* Automated order processing workflow
*/
public function automate_order_processing($order_id) {
$order = wc_get_order($order_id);
if (!$order) {
return;
}
// Check inventory availability
$inventory_check = $this->check_inventory_availability($order);
if (!$inventory_check['available']) {
// Handle backorder
$this->handle_backorder($order, $inventory_check['unavailable_items']);
return;
}
// Allocate inventory
$this->allocate_inventory($order);
// Generate picking list
$picking_list = $this->generate_picking_list($order);
// Send to warehouse management system
$this->send_to_wms($order, $picking_list);
// Update order status
$order->update_status('awaiting-shipment', __('Order sent to fulfillment center', 'woocommerce'));
// Schedule status check
wp_schedule_single_event(
time() + HOUR_IN_SECONDS,
'check_fulfillment_status',
[$order_id]
);
}
/**
* Check inventory availability
*/
private function check_inventory_availability($order) {
$available = true;
$unavailable_items = [];
foreach ($order->get_items() as $item_id => $item) {
$product = $item->get_product();
if (!$product || !$product->managing_stock()) {
continue;
}
$required_qty = $item->get_quantity();
$available_qty = $product->get_stock_quantity();
// Check warehouse availability
$warehouse_stock = $this->get_warehouse_stock($product->get_id());
if ($available_qty + $warehouse_stock < $required_qty) {
$available = false;
$unavailable_items[] = [
'product_id' => $product->get_id(),
'product_name' => $product->get_name(),
'required' => $required_qty,
'available' => $available_qty,
'warehouse' => $warehouse_stock,
];
}
}
return [
'available' => $available,
'unavailable_items' => $unavailable_items,
];
}
/**
* Generate picking list
*/
private function generate_picking_list($order) {
$picking_list = [
'order_id' => $order->get_id(),
'order_number' => $order->get_order_number(),
'created_date' => current_time('mysql'),
'priority' => $this->calculate_order_priority($order),
'items' => [],
];
foreach ($order->get_items() as $item_id => $item) {
$product = $item->get_product();
$picking_list['items'][] = [
'line_item_id' => $item_id,
'product_id' => $product->get_id(),
'sku' => $product->get_sku(),
'name' => $product->get_name(),
'quantity' => $item->get_quantity(),
'location' => get_post_meta($product->get_id(), '_warehouse_location', true),
'weight' => $product->get_weight(),
'dimensions' => [
'length' => $product->get_length(),
'width' => $product->get_width(),
'height' => $product->get_height(),
],
'special_instructions' => $this->get_special_instructions($product),
];
}
// Calculate optimal picking route
$picking_list['route'] = $this->calculate_picking_route($picking_list['items']);
return $picking_list;
}
/**
* Calculate optimal picking route
*/
private function calculate_picking_route($items) {
// Sort items by warehouse location for efficient picking
usort($items, function($a, $b) {
return strcmp($a['location'], $b['location']);
});
$route = [];
$current_zone = '';
foreach ($items as $item) {
$zone = substr($item['location'], 0, 1); // First character is zone
if ($zone !== $current_zone) {
$route[] = [
'zone' => $zone,
'items' => [],
];
$current_zone = $zone;
}
$route[count($route) - 1]['items'][] = [
'location' => $item['location'],
'sku' => $item['sku'],
'quantity' => $item['quantity'],
];
}
return $route;
}
}
// Initialize order manager
new WC_Advanced_Order_Manager();
Shipping and Fulfillment Integration
// Advanced shipping and fulfillment system
class WC_Fulfillment_Integration {
/**
* Initialize fulfillment integration
*/
public function __construct() {
// Shipping calculations
add_filter('woocommerce_package_rates', [$this, 'calculate_shipping_rates'], 10, 2);
// Label generation
add_action('woocommerce_order_action_generate_shipping_label', [$this, 'generate_shipping_label']);
// Tracking integration
add_action('woocommerce_order_shipped', [$this, 'add_tracking_info']);
// Multi-warehouse shipping
add_filter('woocommerce_cart_shipping_packages', [$this, 'split_shipping_packages']);
// Real-time rates
add_action('wp_ajax_get_real_time_rates', [$this, 'ajax_get_real_time_rates']);
add_action('wp_ajax_nopriv_get_real_time_rates', [$this, 'ajax_get_real_time_rates']);
}
/**
* Calculate shipping rates with multiple carriers
*/
public function calculate_shipping_rates($rates, $package) {
// Get package details
$weight = $this->calculate_package_weight($package);
$dimensions = $this->calculate_package_dimensions($package);
$destination = $package['destination'];
// Check cache first
$cache_key = $this->generate_rate_cache_key($package);
$cached_rates = get_transient($cache_key);
if ($cached_rates !== false) {
return $cached_rates;
}
// Get rates from multiple carriers
$carrier_rates = [];
// FedEx
$fedex_rates = $this->get_fedex_rates($weight, $dimensions, $destination);
foreach ($fedex_rates as $rate) {
$carrier_rates[] = $this->format_shipping_rate('fedex', $rate);
}
// UPS
$ups_rates = $this->get_ups_rates($weight, $dimensions, $destination);
foreach ($ups_rates as $rate) {
$carrier_rates[] = $this->format_shipping_rate('ups', $rate);
}
// USPS
$usps_rates = $this->get_usps_rates($weight, $dimensions, $destination);
foreach ($usps_rates as $rate) {
$carrier_rates[] = $this->format_shipping_rate('usps', $rate);
}
// Add carrier rates to WooCommerce rates
foreach ($carrier_rates as $rate) {
$rates[$rate['id']] = $rate;
}
// Cache rates for 1 hour
set_transient($cache_key, $rates, HOUR_IN_SECONDS);
return $rates;
}
/**
* Get FedEx rates
*/
private function get_fedex_rates($weight, $dimensions, $destination) {
$fedex_api = new FedEx_API(
get_option('wc_fedex_account_number'),
get_option('wc_fedex_meter_number'),
get_option('wc_fedex_key'),
get_option('wc_fedex_password')
);
$origin = [
'postal_code' => get_option('woocommerce_store_postcode'),
'country_code' => get_option('woocommerce_default_country'),
];
$rates = $fedex_api->get_rates([
'origin' => $origin,
'destination' => $destination,
'weight' => $weight,
'dimensions' => $dimensions,
'services' => ['FEDEX_GROUND', 'FEDEX_EXPRESS_SAVER', 'PRIORITY_OVERNIGHT'],
]);
return $rates;
}
/**
* Generate shipping label
*/
public function generate_shipping_label($order) {
try {
// Get selected shipping method
$shipping_methods = $order->get_shipping_methods();
$shipping_method = reset($shipping_methods);
if (!$shipping_method) {
throw new Exception(__('No shipping method found', 'woocommerce'));
}
// Parse carrier and service from method ID
list($carrier, $service) = explode(':', $shipping_method->get_method_id());
// Generate label based on carrier
switch ($carrier) {
case 'fedex':
$label_data = $this->generate_fedex_label($order, $service);
break;
case 'ups':
$label_data = $this->generate_ups_label($order, $service);
break;
case 'usps':
$label_data = $this->generate_usps_label($order, $service);
break;
default:
throw new Exception(__('Unsupported carrier', 'woocommerce'));
}
// Save label data
$order->update_meta_data('_shipping_label_url', $label_data['label_url']);
$order->update_meta_data('_tracking_number', $label_data['tracking_number']);
$order->update_meta_data('_shipping_label_cost', $label_data['cost']);
$order->save();
// Add order note
$order->add_order_note(sprintf(
__('Shipping label generated. Tracking: %s', 'woocommerce'),
$label_data['tracking_number']
));
// Send tracking email
do_action('woocommerce_order_shipped', $order->get_id(), $label_data['tracking_number']);
} catch (Exception $e) {
$order->add_order_note(sprintf(
__('Failed to generate shipping label: %s', 'woocommerce'),
$e->getMessage()
));
}
}
/**
* Multi-warehouse package splitting
*/
public function split_shipping_packages($packages) {
if (!WC()->cart || WC()->cart->is_empty()) {
return $packages;
}
// Group items by warehouse
$warehouse_items = [];
foreach (WC()->cart->get_cart() as $cart_item_key => $cart_item) {
$product_id = $cart_item['product_id'];
$warehouse = $this->get_product_warehouse($product_id);
if (!isset($warehouse_items[$warehouse])) {
$warehouse_items[$warehouse] = [];
}
$warehouse_items[$warehouse][$cart_item_key] = $cart_item;
}
// Create separate packages for each warehouse
$packages = [];
$package_index = 1;
foreach ($warehouse_items as $warehouse => $items) {
$packages[] = [
'contents' => $items,
'contents_cost' => array_sum(wp_list_pluck($items, 'line_total')),
'applied_coupons' => WC()->cart->get_applied_coupons(),
'user' => [
'ID' => get_current_user_id(),
],
'destination' => WC()->customer->get_shipping(),
'warehouse' => $warehouse,
'package_name' => sprintf(__('Package %d (Ships from %s)', 'woocommerce'), $package_index, $warehouse),
];
$package_index++;
}
return $packages;
}
}
// Initialize fulfillment integration
new WC_Fulfillment_Integration();
Performance Optimization
WooCommerce Performance Optimization
// Comprehensive WooCommerce performance optimization
class WC_Performance_Optimizer {
/**
* Initialize performance optimizations
*/
public function __construct() {
// Database optimizations
add_action('init', [$this, 'optimize_database_queries']);
// Caching strategies
add_action('init', [$this, 'implement_caching']);
// Asset optimization
add_action('wp_enqueue_scripts', [$this, 'optimize_assets'], 999);
// AJAX optimization
add_filter('woocommerce_ajax_variation_threshold', [$this, 'optimize_ajax_threshold']);
// Background processing
add_action('init', [$this, 'setup_background_processing']);
// Query optimizations
add_filter('woocommerce_product_query_tax_query', [$this, 'optimize_product_queries'], 10, 2);
add_filter('woocommerce_order_data_store_cpt_get_orders_query', [$this, 'optimize_order_queries'], 10, 2);
}
/**
* Optimize database queries
*/
public function optimize_database_queries() {
// Enable HPOS (High-Performance Order Storage)
if (!get_option('woocommerce_hpos_enabled')) {
update_option('woocommerce_feature_custom_order_tables_enabled', 'yes');
}
// Optimize cart session handling
add_filter('woocommerce_session_handler_class', function() {
return 'WC_Session_Handler_Optimized';
});
// Limit transient storage
add_filter('woocommerce_transient_expiration', function($expiration, $transient) {
// Reduce transient expiration for non-critical data
if (strpos($transient, 'wc_product_loop') !== false) {
return HOUR_IN_SECONDS;
}
return $expiration;
}, 10, 2);
// Index optimization
$this->create_performance_indexes();
}
/**
* Create performance indexes
*/
private function create_performance_indexes() {
global $wpdb;
$indexes = [
// Product performance indexes
[
'table' => $wpdb->postmeta,
'name' => 'wc_product_meta_lookup',
'columns' => "post_id, meta_key(20), meta_value(20)",
'condition' => "WHERE meta_key IN ('_price', '_sale_price', '_sku', '_stock')",
],
// Order performance indexes
[
'table' => $wpdb->prefix . 'wc_order_stats',
'name' => 'wc_order_stats_date_status',
'columns' => 'date_created, status(20)',
],
// Customer lookup
[
'table' => $wpdb->prefix . 'wc_customer_lookup',
'name' => 'wc_customer_email',
'columns' => 'email(50)',
],
];
foreach ($indexes as $index) {
$this->create_index_if_not_exists(
$index['table'],
$index['name'],
$index['columns'],
$index['condition'] ?? ''
);
}
}
/**
* Implement caching strategies
*/
public function implement_caching() {
// Product cache warming
add_action('save_post_product', [$this, 'warm_product_cache'], 10, 3);
// Implement fragment caching
add_filter('woocommerce_add_to_cart_fragments', [$this, 'optimize_cart_fragments']);
// Cache expensive calculations
add_filter('woocommerce_calculated_total', [$this, 'cache_cart_calculations'], 10, 2);
// Implement Redis object caching if available
if (class_exists('Redis')) {
$this->setup_redis_caching();
}
}
/**
* Setup Redis caching
*/
private function setup_redis_caching() {
// Initialize Redis connection
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
// Cache product data
add_filter('woocommerce_product_get_price', function($price, $product) use ($redis) {
$cache_key = 'wc_product_price_' . $product->get_id();
$cached_price = $redis->get($cache_key);
if ($cached_price !== false) {
return $cached_price;
}
$redis->setex($cache_key, 3600, $price);
return $price;
}, 10, 2);
// Cache expensive queries
add_filter('posts_pre_query', function($posts, $query) use ($redis) {
if (!$query->is_main_query() || !$query->get('post_type') === 'product') {
return $posts;
}
$cache_key = 'wc_query_' . md5(serialize($query->query_vars));
$cached_results = $redis->get($cache_key);
if ($cached_results !== false) {
return unserialize($cached_results);
}
return $posts;
}, 10, 2);
}
/**
* Optimize assets loading
*/
public function optimize_assets() {
// Remove unnecessary scripts on non-WooCommerce pages
if (!is_woocommerce() && !is_cart() && !is_checkout() && !is_account_page()) {
wp_dequeue_script('wc-cart-fragments');
wp_dequeue_script('woocommerce');
wp_dequeue_script('wc-add-to-cart');
wp_dequeue_style('woocommerce-general');
wp_dequeue_style('woocommerce-layout');
wp_dequeue_style('woocommerce-smallscreen');
}
// Defer non-critical JavaScript
add_filter('script_loader_tag', function($tag, $handle) {
$defer_scripts = [
'wc-add-to-cart-variation',
'wc-single-product',
'wc-geolocation',
];
if (in_array($handle, $defer_scripts)) {
return str_replace(' src', ' defer src', $tag);
}
return $tag;
}, 10, 2);
// Preload critical assets
$this->preload_critical_assets();
}
/**
* Background processing setup
*/
public function setup_background_processing() {
// Process heavy operations in background
add_action('woocommerce_new_order', function($order_id) {
wp_schedule_single_event(time() + 10, 'process_order_analytics', [$order_id]);
});
// Background product sync
add_action('woocommerce_update_product', function($product_id) {
wp_schedule_single_event(time() + 30, 'sync_product_data', [$product_id]);
});
// Batch processing for reports
add_action('woocommerce_after_register_post_type', function() {
if (!wp_next_scheduled('generate_analytics_cache')) {
wp_schedule_event(time(), 'hourly', 'generate_analytics_cache');
}
});
}
}
// Initialize performance optimizer
new WC_Performance_Optimizer();
// Optimized session handler
class WC_Session_Handler_Optimized extends WC_Session_Handler {
/**
* Optimize session cleanup
*/
public function cleanup_sessions() {
global $wpdb;
// Use direct query for better performance
$wpdb->query($wpdb->prepare(
"DELETE FROM {$wpdb->prefix}woocommerce_sessions
WHERE session_expiry < %d
LIMIT 1000",
time()
));
// Schedule next cleanup
wp_schedule_single_event(time() + HOUR_IN_SECONDS, 'woocommerce_cleanup_sessions');
}
}
Security and Compliance
E-commerce Security Implementation
// Comprehensive e-commerce security system
class WC_Security_Manager {
/**
* Initialize security features
*/
public function __construct() {
// PCI compliance
add_action('init', [$this, 'enforce_pci_compliance']);
// Data protection
add_filter('woocommerce_checkout_fields', [$this, 'add_gdpr_consent_fields']);
add_action('woocommerce_checkout_create_order', [$this, 'save_gdpr_consent'], 10, 2);
// Security headers
add_action('send_headers', [$this, 'add_security_headers']);
// Input validation
add_action('woocommerce_checkout_process', [$this, 'validate_checkout_security']);
// API security
add_filter('woocommerce_api_check_authentication', [$this, 'enhance_api_security'], 10, 2);
// File upload security
add_filter('upload_mimes', [$this, 'restrict_upload_mimes']);
add_filter('wp_handle_upload_prefilter', [$this, 'scan_uploaded_files']);
}
/**
* Enforce PCI compliance
*/
public function enforce_pci_compliance() {
// Force SSL on checkout
if (is_checkout() && !is_ssl()) {
wp_redirect('https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'], 301);
exit;
}
// Disable card storage
add_filter('woocommerce_payment_gateways_save_payment_method_checkbox', '__return_false');
// Implement Content Security Policy
add_action('wp_head', function() {
if (is_checkout()) {
?>
<meta http-equiv="Content-Security-Policy" content="
default-src 'self';
script-src 'self' 'unsafe-inline' https://js.stripe.com https://checkout.paypal.com;
style-src 'self' 'unsafe-inline';
img-src 'self' data: https:;
connect-src 'self' https://api.stripe.com;
frame-src 'self' https://js.stripe.com https://checkout.paypal.com;
">
<?php
}
});
}
/**
* Add security headers
*/
public function add_security_headers() {
header('X-Content-Type-Options: nosniff');
header('X-Frame-Options: SAMEORIGIN');
header('X-XSS-Protection: 1; mode=block');
header('Referrer-Policy: strict-origin-when-cross-origin');
header('Permissions-Policy: geolocation=(), microphone=(), camera=()');
if (is_ssl()) {
header('Strict-Transport-Security: max-age=31536000; includeSubDomains');
}
}
/**
* GDPR compliance
*/
public function add_gdpr_consent_fields($fields) {
$fields['order']['gdpr_consent'] = [
'type' => 'checkbox',
'label' => __('I consent to the storage and processing of my data in accordance with the privacy policy', 'woocommerce'),
'required' => true,
'class' => ['gdpr-consent-field'],
'priority' => 999,
];
return $fields;
}
/**
* Validate checkout security
*/
public function validate_checkout_security() {
// Rate limiting
$this->check_checkout_rate_limit();
// Validate nonce
if (!wp_verify_nonce($_POST['woocommerce-process-checkout-nonce'], 'woocommerce-process_checkout')) {
wc_add_notice(__('Security check failed. Please refresh and try again.', 'woocommerce'), 'error');
}
// Check for suspicious patterns
$this->detect_malicious_input($_POST);
// Validate email format strictly
if (!filter_var($_POST['billing_email'], FILTER_VALIDATE_EMAIL)) {
wc_add_notice(__('Please enter a valid email address.', 'woocommerce'), 'error');
}
}
/**
* Detect malicious input
*/
private function detect_malicious_input($data) {
$suspicious_patterns = [
'/<script[^>]*>.*?<\/script>/is',
'/on\w+\s*=\s*["\'].*?["\']/i',
'/javascript\s*:/i',
'/base64_decode/i',
'/eval\s*\(/i',
'/exec\s*\(/i',
];
foreach ($data as $key => $value) {
if (is_string($value)) {
foreach ($suspicious_patterns as $pattern) {
if (preg_match($pattern, $value)) {
wc_add_notice(__('Invalid input detected. Please check your data.', 'woocommerce'), 'error');
// Log security event
$this->log_security_event('malicious_input', [
'field' => $key,
'pattern' => $pattern,
'ip' => $_SERVER['REMOTE_ADDR'],
]);
return;
}
}
}
}
}
/**
* Enhanced API security
*/
public function enhance_api_security($user, $consumer) {
// Implement OAuth 2.0
if (get_option('woocommerce_api_oauth2_enabled')) {
return $this->validate_oauth2_token();
}
// Rate limiting for API
$this->check_api_rate_limit($consumer);
// IP whitelist check
if (!$this->is_ip_whitelisted($_SERVER['REMOTE_ADDR'])) {
return new WP_Error('forbidden', __('Access denied from this IP', 'woocommerce'), ['status' => 403]);
}
return $user;
}
}
// Initialize security manager
new WC_Security_Manager();
Advanced Features and Integrations
Multi-vendor Marketplace
// Multi-vendor marketplace implementation
class WC_Multivendor_Marketplace {
/**
* Initialize marketplace features
*/
public function __construct() {
// Vendor registration
add_action('init', [$this, 'register_vendor_role']);
add_shortcode('vendor_registration', [$this, 'vendor_registration_form']);
// Vendor dashboard
add_action('init', [$this, 'add_vendor_endpoints']);
add_filter('woocommerce_account_menu_items', [$this, 'add_vendor_menu_items']);
// Product management
add_filter('woocommerce_product_data_store_cpt_get_products_query', [$this, 'filter_vendor_products'], 10, 2);
// Commission management
add_action('woocommerce_order_status_completed', [$this, 'calculate_vendor_commission']);
// Vendor shipping
add_filter('woocommerce_package_rates', [$this, 'vendor_shipping_rates'], 10, 2);
}
/**
* Register vendor role
*/
public function register_vendor_role() {
add_role('vendor', __('Vendor', 'woocommerce'), [
'read' => true,
'edit_posts' => false,
'delete_posts' => false,
'publish_posts' => false,
'upload_files' => true,
// Product capabilities
'edit_products' => true,
'publish_products' => false, // Require approval
'read_private_products' => true,
'delete_products' => true,
'edit_private_products' => true,
'delete_private_products' => true,
'edit_published_products' => true,
'delete_published_products' => true,
// Shop order capabilities
'read_shop_orders' => true,
'edit_shop_orders' => true,
]);
}
/**
* Vendor registration form
*/
public function vendor_registration_form() {
if (is_user_logged_in()) {
return '<p>' . __('You are already registered.', 'woocommerce') . '</p>';
}
ob_start();
?>
<form method="post" class="vendor-registration-form">
<?php wp_nonce_field('vendor_registration', 'vendor_nonce'); ?>
<p class="form-row">
<label for="vendor_name"><?php esc_html_e('Store Name', 'woocommerce'); ?> <span class="required">*</span></label>
<input type="text" class="input-text" name="vendor_name" id="vendor_name" required />
</p>
<p class="form-row">
<label for="vendor_email"><?php esc_html_e('Email', 'woocommerce'); ?> <span class="required">*</span></label>
<input type="email" class="input-text" name="vendor_email" id="vendor_email" required />
</p>
<p class="form-row">
<label for="vendor_description"><?php esc_html_e('Store Description', 'woocommerce'); ?></label>
<textarea name="vendor_description" id="vendor_description" rows="4"></textarea>
</p>
<p class="form-row">
<label for="vendor_location"><?php esc_html_e('Location', 'woocommerce'); ?></label>
<input type="text" class="input-text" name="vendor_location" id="vendor_location" />
</p>
<p class="form-row">
<label for="vendor_paypal"><?php esc_html_e('PayPal Email (for payments)', 'woocommerce'); ?> <span class="required">*</span></label>
<input type="email" class="input-text" name="vendor_paypal" id="vendor_paypal" required />
</p>
<p class="form-row">
<button type="submit" class="button" name="register_vendor"><?php esc_html_e('Register as Vendor', 'woocommerce'); ?></button>
</p>
</form>
<?php
return ob_get_clean();
}
/**
* Calculate vendor commission
*/
public function calculate_vendor_commission($order_id) {
$order = wc_get_order($order_id);
if (!$order) {
return;
}
$vendor_commissions = [];
foreach ($order->get_items() as $item) {
$product = $item->get_product();
$vendor_id = get_post_field('post_author', $product->get_id());
if (!user_can($vendor_id, 'vendor')) {
continue;
}
// Get commission rate
$commission_rate = $this->get_vendor_commission_rate($vendor_id, $product);
// Calculate commission
$line_total = $item->get_total();
$commission = $line_total * ($commission_rate / 100);
if (!isset($vendor_commissions[$vendor_id])) {
$vendor_commissions[$vendor_id] = 0;
}
$vendor_commissions[$vendor_id] += $commission;
}
// Save commissions
foreach ($vendor_commissions as $vendor_id => $commission) {
$this->create_commission_record($order_id, $vendor_id, $commission);
}
}
/**
* Get vendor commission rate
*/
private function get_vendor_commission_rate($vendor_id, $product) {
// Check product-specific rate
$product_rate = get_post_meta($product->get_id(), '_vendor_commission_rate', true);
if ($product_rate) {
return floatval($product_rate);
}
// Check vendor-specific rate
$vendor_rate = get_user_meta($vendor_id, 'commission_rate', true);
if ($vendor_rate) {
return floatval($vendor_rate);
}
// Check category-specific rate
$categories = wp_get_post_terms($product->get_id(), 'product_cat', ['fields' => 'ids']);
foreach ($categories as $cat_id) {
$cat_rate = get_term_meta($cat_id, 'vendor_commission_rate', true);
if ($cat_rate) {
return floatval($cat_rate);
}
}
// Default rate
return floatval(get_option('default_vendor_commission_rate', 80));
}
}
// Initialize marketplace
new WC_Multivendor_Marketplace();
Advanced Analytics and Reporting
// Advanced analytics system
class WC_Advanced_Analytics {
/**
* Initialize analytics
*/
public function __construct() {
// Custom reports
add_filter('woocommerce_admin_reports', [$this, 'add_custom_reports']);
// Real-time analytics
add_action('woocommerce_new_order', [$this, 'track_real_time_sale']);
add_action('woocommerce_add_to_cart', [$this, 'track_add_to_cart']);
// Customer analytics
add_action('woocommerce_created_customer', [$this, 'track_customer_acquisition']);
// Product analytics
add_action('woocommerce_before_single_product', [$this, 'track_product_view']);
// Export functionality
add_action('admin_init', [$this, 'handle_analytics_export']);
}
/**
* Add custom reports
*/
public function add_custom_reports($reports) {
$reports['advanced'] = [
'title' => __('Advanced Analytics', 'woocommerce'),
'reports' => [
'cohort_analysis' => [
'title' => __('Cohort Analysis', 'woocommerce'),
'description' => __('Analyze customer behavior over time', 'woocommerce'),
'callback' => [$this, 'cohort_analysis_report'],
],
'product_performance' => [
'title' => __('Product Performance', 'woocommerce'),
'description' => __('Detailed product analytics', 'woocommerce'),
'callback' => [$this, 'product_performance_report'],
],
'customer_lifetime_value' => [
'title' => __('Customer Lifetime Value', 'woocommerce'),
'description' => __('CLV analysis and predictions', 'woocommerce'),
'callback' => [$this, 'clv_report'],
],
'conversion_funnel' => [
'title' => __('Conversion Funnel', 'woocommerce'),
'description' => __('Shopping cart abandonment analysis', 'woocommerce'),
'callback' => [$this, 'conversion_funnel_report'],
],
],
];
return $reports;
}
/**
* Cohort analysis report
*/
public function cohort_analysis_report() {
global $wpdb;
// Get cohorts by month
$cohorts = $wpdb->get_results("
SELECT
DATE_FORMAT(date_registered, '%Y-%m') as cohort_month,
COUNT(DISTINCT user_id) as customers
FROM {$wpdb->prefix}wc_customer_lookup
WHERE date_registered >= DATE_SUB(NOW(), INTERVAL 12 MONTH)
GROUP BY cohort_month
ORDER BY cohort_month
");
$cohort_data = [];
foreach ($cohorts as $cohort) {
$cohort_month = $cohort->cohort_month;
// Get retention data for each month
for ($month = 0; $month <= 12; $month++) {
$retention = $wpdb->get_var($wpdb->prepare("
SELECT COUNT(DISTINCT o.customer_id) / %d * 100
FROM {$wpdb->prefix}wc_order_stats o
JOIN {$wpdb->prefix}wc_customer_lookup c ON o.customer_id = c.customer_id
WHERE DATE_FORMAT(c.date_registered, '%%Y-%%m') = %s
AND DATE_FORMAT(o.date_created, '%%Y-%%m') = DATE_FORMAT(DATE_ADD(c.date_registered, INTERVAL %d MONTH), '%%Y-%%m')
AND o.status IN ('wc-completed', 'wc-processing')
", $cohort->customers, $cohort_month, $month));
$cohort_data[$cohort_month][$month] = round($retention, 1);
}
}
$this->render_cohort_table($cohort_data);
}
/**
* Customer lifetime value calculation
*/
public function calculate_customer_lifetime_value($customer_id) {
global $wpdb;
// Get customer order history
$order_data = $wpdb->get_row($wpdb->prepare("
SELECT
COUNT(*) as order_count,
SUM(total_sales) as total_spent,
MIN(date_created) as first_order,
MAX(date_created) as last_order,
AVG(total_sales) as avg_order_value
FROM {$wpdb->prefix}wc_order_stats
WHERE customer_id = %d
AND status IN ('wc-completed', 'wc-processing')
", $customer_id));
if (!$order_data || $order_data->order_count == 0) {
return 0;
}
// Calculate customer age in days
$customer_age_days = (strtotime($order_data->last_order) - strtotime($order_data->first_order)) / 86400;
$customer_age_days = max($customer_age_days, 1);
// Calculate purchase frequency (orders per year)
$purchase_frequency = ($order_data->order_count / $customer_age_days) * 365;
// Estimate customer lifespan (years)
$churn_rate = $this->calculate_churn_rate();
$customer_lifespan = 1 / $churn_rate;
// CLV = Average Order Value × Purchase Frequency × Customer Lifespan
$clv = $order_data->avg_order_value * $purchase_frequency * $customer_lifespan;
return round($clv, 2);
}
}
// Initialize analytics
new WC_Advanced_Analytics();
Next Steps and Resources
With this comprehensive foundation in WooCommerce development, you're equipped to build sophisticated e-commerce solutions. To continue advancing your skills:
Explore Our Cluster Articles
-
Custom WooCommerce Product Types: Beyond Simple Products - Deep dive into creating subscription products, bookable items, and custom product types
-
Building a WooCommerce Payment Gateway from Scratch - Step-by-step guide to creating secure payment integrations
-
WooCommerce REST API: Building Headless Commerce - Implement headless e-commerce with modern JavaScript frameworks
-
Optimizing WooCommerce for High-Traffic Stores - Advanced performance techniques for scaling
-
WooCommerce Multi-Vendor Marketplace Development - Build complex marketplace platforms
-
Advanced WooCommerce Shipping Solutions - Implement dynamic shipping calculations and integrations
-
WooCommerce Subscription Products: Complete Guide - Create recurring revenue with subscription products
-
WooCommerce B2B Features and Wholesale - Implement B2B functionality and wholesale pricing
-
WooCommerce Security Best Practices - Comprehensive security implementation for e-commerce
Key Takeaways
- Architecture Understanding: Master WooCommerce's database structure and hooks system
- Custom Development: Create custom product types, payment gateways, and shipping methods
- Performance Focus: Implement caching, optimize queries, and scale effectively
- Security First: Always prioritize PCI compliance and data protection
- User Experience: Build intuitive interfaces that convert visitors to customers
Continue Learning
- Join the Community: Participate in WooCommerce developer forums and contribute to open source
- Stay Updated: Follow WooCommerce development blog for latest features and best practices
- Build Projects: Create real-world e-commerce solutions to apply your knowledge
- Get Certified: Consider WooCommerce developer certification for credibility
Remember, successful e-commerce development combines technical expertise with understanding business needs. Focus on creating solutions that drive conversions while maintaining performance and security.
Last updated: July 12, 2025