Розробка користувальницького плагіна WooCommerce
WooCommerce побудований на хуках WordPress і надає власний шар хуків поверх — action та filter для кожного етапу жизненного циклу замовлення, товара, платежу. Користувальницький плагін WooCommerce — це бізнес-логіка, яка не покривається ні стандартним WooCommerce, ні готовими аддонами: специфічне ціноутворення, інтеграція з внутрішньою ERP, нестандартні типи скидок, користувальницькі статусі замовлень. Розробка плагіна середної складності — 5–10 робочих днів.
Базова структура та перевірка залежностей
<?php
/**
* Plugin Name: My WooCommerce Extension
* WC requires at least: 8.0
* WC tested up to: 9.0
*/
defined('ABSPATH') || exit;
// Перевіряємо наявність WooCommerce перед активацією
register_activation_hook(__FILE__, function () {
if (!class_exists('WooCommerce')) {
deactivate_plugins(plugin_basename(__FILE__));
wp_die('Потрібен WooCommerce 8.0+');
}
});
// Безпечна ініціалізація після завантаження WooCommerce
add_action('woocommerce_loaded', function () {
require_once plugin_dir_path(__FILE__) . 'includes/class-main.php';
My_WC_Plugin::instance();
});
// Декларуємо сумісність з HPOS (High-Performance Order Storage)
add_action('before_woocommerce_init', function () {
if (class_exists(\Automattic\WooCommerce\Utilities\FeaturesUtil::class)) {
\Automattic\WooCommerce\Utilities\FeaturesUtil::declare_compatibility(
'custom_order_tables',
__FILE__,
true
);
}
});
Користувальницькі статуси замовлень
// Реєстрація статусу
add_action('init', function () {
register_post_status('wc-awaiting-delivery', [
'label' => 'Очікує доставки',
'public' => true,
'show_in_admin_status_list' => true,
'show_in_admin_all_list' => true,
'exclude_from_search' => false,
'label_count' => _n_noop(
'Очікує доставки <span class="count">(%s)</span>',
'Очікує доставки <span class="count">(%s)</span>'
),
]);
});
// Додавання в список WooCommerce
add_filter('wc_order_statuses', function (array $statuses): array {
$statuses['wc-awaiting-delivery'] = 'Очікує доставки';
return $statuses;
});
// Колір в списку замовлень
add_filter('woocommerce_admin_order_statuses_list_badge', function (array $badges): array {
$badges['awaiting-delivery'] = '#f59e0b'; // amber
return $badges;
});
// Email при переході в новий статус
add_action('woocommerce_order_status_awaiting-delivery', function (int $order_id): void {
$order = wc_get_order($order_id);
// відправка листа клієнту
WC()->mailer()->customer_new_account($order->get_billing_email());
});
Користувальницька система скидок
Приклад: скидка на основі накопленних замовлень клієнта:
add_filter('woocommerce_cart_totals_coupon_label', '__return_false'); // скривиємо стандартний купон
add_action('woocommerce_cart_calculate_fees', function (WC_Cart $cart): void {
if (is_admin() && !defined('DOING_AJAX')) return;
$user_id = get_current_user_id();
if (!$user_id) return;
$total_spent = wc_get_customer_total_spent($user_id);
$discount_pct = 0;
if ($total_spent >= 100000) {
$discount_pct = 10;
} elseif ($total_spent >= 50000) {
$discount_pct = 7;
} elseif ($total_spent >= 20000) {
$discount_pct = 5;
}
if ($discount_pct > 0) {
$cart_subtotal = $cart->get_subtotal();
$discount = -($cart_subtotal * $discount_pct / 100);
$cart->add_fee(
sprintf('Накопительна скидка %d%%', $discount_pct),
$discount,
true // облагається податком
);
}
});
Користувальницькі поля товара
Додавання вкладки з полями в редакторі товара:
// Додаємо вкладку
add_filter('woocommerce_product_data_tabs', function (array $tabs): array {
$tabs['production_info'] = [
'label' => 'Виробництво',
'target' => 'production_info_data',
'class' => ['show_if_simple', 'show_if_variable'],
'priority' => 80,
];
return $tabs;
});
// Вміст вкладки
add_action('woocommerce_product_data_panels', function (): void {
global $thepostid;
?>
<div id="production_info_data" class="panel woocommerce_options_panel">
<?php
woocommerce_wp_text_input([
'id' => '_manufacturer',
'label' => 'Виробник',
'placeholder' => 'Назва компанії',
'value' => get_post_meta($thepostid, '_manufacturer', true),
]);
woocommerce_wp_select([
'id' => '_certification',
'label' => 'Сертифікація',
'options' => [
'' => 'Не вказано',
'gost' => 'ГОСТ',
'iso' => 'ISO 9001',
'ce' => 'CE',
],
'value' => get_post_meta($thepostid, '_certification', true),
]);
?>
</div>
<?php
});
// Збереження
add_action('woocommerce_process_product_meta', function (int $post_id): void {
update_post_meta($post_id, '_manufacturer', sanitize_text_field($_POST['_manufacturer'] ?? ''));
update_post_meta($post_id, '_certification', sanitize_key($_POST['_certification'] ?? ''));
});
Фонові задачі та черги
Для тяжких операцій (синхронізація остатків, масове оновлення цін) використовуємо WooCommerce Action Scheduler:
// Плануємо задачу
as_schedule_single_action(
time() + 60,
'my_plugin_sync_stock',
['supplier_id' => 42],
'my-plugin'
);
// Обробник
add_action('my_plugin_sync_stock', function (int $supplier_id): void {
$items = fetch_supplier_stock($supplier_id);
foreach ($items as $sku => $qty) {
$product_id = wc_get_product_id_by_sku($sku);
if ($product_id) {
$product = wc_get_product($product_id);
$product->set_stock_quantity($qty);
$product->save();
}
}
});
Action Scheduler — production-ready черга задач, вбудована в WooCommerce. Зберігає задачі в БД, повторяє при помилках, має UI в /wp-admin → Інструменти → Запланові дії.
Типові терміни: плагін з користувальницькими полями товара та статусами — 3–4 дні. Плагін з користувальницькою логікою скидок, інтеграцією з зовнішнім API та фоновими задачами — 8–12 днів.







