Разработка плагинов для WooCommerce
Разработка плагинов для WooCommerce требует понимания WordPress и WooCommerce API. Вот пошаговое руководство:
1. Подготовка среды разработки
- Установите локальный сервер (XAMPP, MAMP, Local by Flywheel).
- Установите WordPress и WooCommerce.
- Включите
WP_DEBUG
вwp-config.php
для отладки.
2. Создание базовой структуры плагина
- В папке
/wp-content/plugins/
создайте папку для плагина (напр.,my-woocommerce-addon
). - Создайте основной файл плагина (напр.,
my-woocommerce-addon.php
) с заголовком:
<?php
/**
* Plugin Name: My WooCommerce Addon
* Description: Custom functionality for WooCommerce.
* Version: 1.0.0
* Author: Your Name
*/
3. Подключение к WooCommerce
Убедитесь, что WooCommerce активен, прежде чем выполнять код:
if (class_exists('WooCommerce')) {
// Ваш код
}
4. Основные методы расширения WooCommerce
Добавление полей в товар
add_action('woocommerce_product_options_general_product_data', 'my_custom_field');
function my_custom_field() {
woocommerce_wp_text_input([
'id' => 'my_custom_field',
'label' => 'Custom Field',
'placeholder' => 'Enter value',
]);
}
// Сохранение поля
add_action('woocommerce_process_product_meta', 'save_custom_field');
function save_custom_field($post_id) {
$custom_field = $_POST['my_custom_field'] ?? '';
update_post_meta($post_id, 'my_custom_field', sanitize_text_field($custom_field));
}
Добавление вкладки в товар
add_filter('woocommerce_product_tabs', 'add_custom_tab');
function add_custom_tab($tabs) {
$tabs['custom_tab'] = [
'title' => 'Custom Tab',
'priority' => 50,
'callback' => 'custom_tab_content'
];
return $tabs;
}
function custom_tab_content() {
echo '<h2>Custom Tab Content</h2>';
}
Кастомизация корзины
add_filter('woocommerce_add_cart_item_data', 'add_custom_data_to_cart', 10, 3);
function add_custom_data_to_cart($cart_item_data, $product_id, $variation_id) {
if (isset($_POST['my_custom_data'])) {
$cart_item_data['my_custom_data'] = sanitize_text_field($_POST['my_custom_data']);
}
return $cart_item_data;
}
Добавление кастомного типа оплаты
add_filter('woocommerce_payment_gateways', 'add_custom_gateway');
function add_custom_gateway($gateways) {
$gateways[] = 'WC_Custom_Gateway';
return $gateways;
}
// Класс платежного шлюза
class WC_Custom_Gateway extends WC_Payment_Gateway {
public function __construct() {
$this->id = 'custom_gateway';
$this->method_title = 'Custom Gateway';
$this->init_form_fields();
$this->init_settings();
add_action('woocommerce_update_options_payment_gateways_' . $this->id, [$this, 'process_admin_options']);
}
public function init_form_fields() {
$this->form_fields = [
'enabled' => [
'title' => 'Enable/Disable',
'type' => 'checkbox',
'label' => 'Enable Custom Gateway',
'default' => 'yes'
]
];
}
public function process_payment($order_id) {
// Логика обработки платежа
}
}
5. Добавление стилей и скриптов
add_action('wp_enqueue_scripts', 'my_plugin_scripts');
function my_plugin_scripts() {
wp_enqueue_style('my-plugin-style', plugins_url('assets/css/style.css', __FILE__));
wp_enqueue_script('my-plugin-script', plugins_url('assets/js/script.js', __FILE__), ['jquery'], '1.0', true);
}
6. Проверка совместимости
- Используйте хуки WooCommerce (напр.,
woocommerce_before_add_to_cart_button
). - Проверяйте версию WooCommerce:
if (version_compare(WC_VERSION, '5.0', '<')) {
// Код для старых версий
}
7. Тестирование
- Проверьте работу плагина с разными темами.
- Протестируйте на последней версии WooCommerce.
8. Публикация
- Упакуйте плагин в ZIP.
- Загрузите в репозиторий WordPress или продавайте на CodeCanyon.
Полезные ссылки:
Готовый пример можно найти на GitHub WooCommerce Samples.