Main/WordPress Fullstack/Blueprints/WooCommerce/Custom Variation Swatches & AJAX Threshold Bypass for 50+ Variations
Back to «WooCommerce» cards
WooCommerce(ТЗ 39 из 54)
Spec: Custom Variation Swatches & AJAX Threshold Bypass for 50+ Variations
WooCommerce5 шагов • +25 XP

Spec: Custom Variation Swatches & AJAX Threshold Bypass for 50+ Variations

High-performance variation selector engineering: replacing ugly dropdowns with color/image/button swatches, overriding the 30-variation AJAX threshold (woocommerce_ajax_variation_threshold), preloading variation data, and styling out-of-stock states.

~10 ч работыУровень: MiddleCustom Variation Swatcheswoocommerce_ajax_variation_thresholdVanilla JavaScriptWooCommerce REST/AJAX EndpointsCSS Flexbox/GridGallery Image Sync
+5 XP за шаг
Выполнено 0 из 5 шагов (0%)
Трудозатраты~10 рабочих часов
Фриланс вилка~$450 – $750 (€400 – €700)
Оценка веб-студии~$950 – $1,600 (€900 – €1500)

ТЗ заказчика (исходный бриф):

Our clothing store has products with 60+ variations (colors, sizes, fabrics). The default select dropdowns are clumsy, and WooCommerce stops preloading variations via AJAX after 30 items, causing a sluggish delay when picking sizes.
Ключевые требования:
  • •Custom swatch buttons (color circles, image previews, size pills) replacing default HTML selects
  • •Custom attribute taxonomy meta fields for hex colors and thumbnail images
  • •Filter woocommerce_ajax_variation_threshold to safely raise the threshold for rich client preloading
  • •Visual indicators for disabled/out-of-stock attribute combinations
  • •WCAG 2.1 AA keyboard accessibility (radio-group ARIA semantics)
Ограничения проекта:
  • •Zero heavy third-party swatch plugins that inject 500KB of unminified CSS/JS
  • •Preserve standard WooCommerce variation form events (found_variation, reset_data)
  • •Optimized JSON payload size when sending variation data to frontend
Критерии приёмки (KPI):
  • Variation switch response time < 50ms (zero AJAX lag)
  • Conversion rate increase of 15%+ on variable products
  • Lighthouse Accessibility score = 100 on product detail page

Конфигурация блупринта под условия проекта

Выберите архитектуру и стек — шаги роадмапа, структура файлов и примеры кода переключатся автоматически:

Пошаговое практическое руководство по ТЗ

Подробный разбор архитектуры, код реализации и советы эксперта по каждому этапу:

1
Этап 1 из 5

Step 1: Attribute taxonomy meta fields for color & image

~40 минСредний

Практическое руководство:

In functions.php, add custom fields to attribute taxonomies (e.g. pa_color, pa_size). Store color hex codes and attachment image IDs using add_term_meta() and update_term_meta().

План и контрольные точки реализации:
1Подключить хуки pa_color_add_form_fields и pa_color_edit_form_fields
2Подключить скрипт wp-color-picker в админке
3Сохранять мета-поле hex_color через update_term_meta
Важные технические нюансы и подводные камни:

Sanitize hex colors with sanitize_hex_color() before saving to term meta.

Совет эксперта (Best Practice):

Использование sanitize_hex_color(): Всегда применяйте sanitize_hex_color() вместо общего sanitize_text_field(), чтобы исключить сохранение некорректных значений цвета в базу. (Важно: Если цвет не задан, используйте заглушку #e2e8f0, чтобы кнопка не отображалась прозрачной.)

Ожидаемый артефакт этапа:

Удобная настройка цветов для каждого оттенка прямо в панели атрибутов WooCommerce.

PHP
<?php
declare(strict_types=1);

add_action('pa_color_add_form_fields', function () {
    ?>
    <div class="form-field">
        <label for="term_color"><?php esc_html_e('Цвет плашки (HEX)', 'agenticlab'); ?></label>
        <input type="text" name="term_color" id="term_color" class="agenticlab-color-picker" value="#ffffff" />
    </div>
    <?php
});

add_action('pa_color_edit_form_fields', function ($term) {
    $color = get_term_meta($term->term_id, 'term_color', true) ?: '#ffffff';
    ?>
    <tr class="form-field">
        <th scope="row"><label for="term_color"><?php esc_html_e('Цвет плашки (HEX)', 'agenticlab'); ?></label></th>
        <td>
            <input type="text" name="term_color" id="term_color" class="agenticlab-color-picker" value="<?php echo esc_attr($color); ?>" />
        </td>
    </tr>
    <?php
});

add_action('admin_enqueue_scripts', function ($hook) {
    if (in_array($hook, ['edit-tags.php', 'term.php'], true)) {
        wp_enqueue_style('wp-color-picker');
        wp_enqueue_script('wp-color-picker');
        wp_add_inline_script('wp-color-picker', 'jQuery(document).ready(function($){ $(".agenticlab-color-picker").wpColorPicker(); });');
    }
});

add_action('saved_pa_color', function ($term_id) {
    if (isset($_POST['term_color'])) {
        update_term_meta($term_id, 'term_color', sanitize_hex_color($_POST['term_color']));
    }
});
2
Этап 2 из 5

Step 2: Raising AJAX threshold via woocommerce_ajax_variation_threshold

~45 минСредний
3
Этап 3 из 5

Step 3: Custom frontend swatch markup & ARIA radio semantics

~45 минСредний
4
Этап 4 из 5

Step 4: Client JavaScript controller & out-of-stock state styling

~50 минСложный
5
Этап 5 из 5

Step 5: Mobile touch optimization & keyboard accessibility QA

~30 минЛегкий

Типичные грабли на этом ТЗ

2 антипаттерна

Инструменты экосистемы Fullstack AI Lab для этого ТЗ

Интеграция