سازنده هوشمند فهرست دسته‌بندی محصولات ووکامرس | WooCommerce Category Menu Builder

سازنده هوشمند فهرست دسته‌بندی محصولات ووکامرس | WooCommerce Category Menu Builder

سازنده هوشمند فهرست دسته‌بندی محصولات ووکامرس 🛍️ مدیریت دسته‌بندی محصولات یکی از بخش‌های مهم هر فروشگاه اینترنتی است. زمانی که تعداد دسته‌ها و زیرمجموعه‌های محصولات افزایش پیدا می‌کند، ایجاد دستی فهرست‌های ناوبری در وردپرس می‌تواند زمان‌بر و دشوار باشد. افزونه سازنده هوشمند فهرست دسته‌بندی محصولات ووکامرس، راهکاری کاربردی برای شناسایی

کد
/**
 * WooCommerce Categories Menu Builder
 * Version: 3.0
 *
 * Scan existing WooCommerce categories
 * Create WordPress menu: دسته محصولات
 * Preserve parent-child hierarchy
 * AJAX progress / Stop / Resume
 *
 * Does NOT create, delete or edit WooCommerce categories.
 */

if (!defined('ABSPATH')) {
    exit;
}


/* =====================================================
   1. CONFIGURATION AND HELPERS
===================================================== */

function wcmb3_key($name) {
    return 'wcmb3_' . $name . '_' . get_current_user_id();
}

function wcmb3_check_ajax() {

    check_ajax_referer('wcmb3_nonce', 'nonce');

    if (!current_user_can('edit_theme_options')) {
        wp_send_json_error([
            'message' => 'شما دسترسی مدیریت فهرست‌های وردپرس را ندارید.'
        ], 403);
    }

    if (!taxonomy_exists('product_cat')) {
        wp_send_json_error([
            'message' => 'دسته‌بندی محصولات ووکامرس در دسترس نیست.'
        ]);
    }
}

function wcmb3_find_menu() {

    $menu = wp_get_nav_menu_object('دسته محصولات');

    if (!$menu) {
        return false;
    }

    return $menu;
}


/* =====================================================
   2. SCAN ALL EXISTING WOOCOMMERCE CATEGORIES
===================================================== */

function wcmb3_scan_categories() {

    $terms = get_terms([
        'taxonomy'   => 'product_cat',
        'hide_empty' => false,
        'orderby'    => 'name',
        'order'      => 'ASC'
    ]);

    if (is_wp_error($terms)) {
        return $terms;
    }

    $term_map = [];
    $parents = [];

    foreach ($terms as $term) {
        $term_map[(int) $term->term_id] = $term;
    }

    // Normalize category parent relationships
    foreach ($terms as $term) {

        $id = (int) $term->term_id;
        $parent = (int) $term->parent;

        if (
            $parent === $id ||
            ($parent !== 0 && !isset($term_map[$parent]))
        ) {
            $parent = 0;
        }

        $parents[$id] = $parent;
    }

    $children = [];

    foreach ($terms as $term) {

        $id = (int) $term->term_id;
        $parent = $parents[$id];

        if (!isset($children[$parent])) {
            $children[$parent] = [];
        }

        $children[$parent][] = $term;
    }

    // Alphabetical ordering within each parent
    foreach ($children as &$group) {

        usort($group, function ($a, $b) {
            return strnatcasecmp($a->name, $b->name);
        });

    }

    unset($group);

    $ordered = [];
    $visited = [];

    // Recursive hierarchy traversal
    $walk = function ($parent_id, $depth) use (
        &$walk,
        &$children,
        &$parents,
        &$ordered,
        &$visited
    ) {

        if (empty($children[$parent_id])) {
            return;
        }

        foreach ($children[$parent_id] as $term) {

            $id = (int) $term->term_id;

            if (isset($visited[$id])) {
                continue;
            }

            $visited[$id] = true;

            $ordered[] = [
                'term_id'   => $id,
                'parent_id' => $parents[$id],
                'name'      => $term->name,
                'slug'      => $term->slug,
                'depth'     => $depth
            ];

            $walk($id, $depth + 1);
        }
    };

    // Start from root categories
    $walk(0, 0);

    // Include unusual disconnected/cyclic terms
    foreach ($terms as $term) {

        $id = (int) $term->term_id;

        if (isset($visited[$id])) {
            continue;
        }

        // Break invalid cycle by treating this item as a root
        $visited[$id] = true;

        $ordered[] = [
            'term_id'   => $id,
            'parent_id' => 0,
            'name'      => $term->name,
            'slug'      => $term->slug,
            'depth'     => 0
        ];

        $walk($id, 1);
    }

    return $ordered;
}


/* =====================================================
   3. ADMIN MENU
===================================================== */

add_action('admin_menu', function () {

    if (!class_exists('WooCommerce')) {
        return;
    }

    add_submenu_page(
        'edit.php?post_type=product',
        'سازنده فهرست دسته محصولات',
        'سازنده فهرست دسته‌ها',
        'edit_theme_options',
        'wcmb3-builder',
        'wcmb3_admin_page'
    );

}, 99);


/* =====================================================
   4. ADMIN DASHBOARD
===================================================== */

function wcmb3_admin_page() {

    if (!current_user_can('edit_theme_options')) {
        return;
    }

    wp_enqueue_script('jquery');

    $config = [
        'ajax'  => admin_url('admin-ajax.php'),
        'nonce' => wp_create_nonce('wcmb3_nonce')
    ];

    ?>

    <div class="wrap wcmb3-dashboard" dir="rtl">

        <style>

        .wcmb3-dashboard {
            max-width: 1100px;
            margin: 25px auto;
            font-family: inherit;
        }

        .wcmb3-dashboard *,
        .wcmb3-dashboard *:before,
        .wcmb3-dashboard *:after {
            box-sizing: border-box;
        }

        .wcmb3-header {
            background: linear-gradient(120deg,#172554,#2563eb);
            color: #fff;
            padding: 30px;
            border-radius: 17px;
            margin-bottom: 22px;
        }

        .wcmb3-header h1 {
            color: #fff;
            font-size: 23px;
            margin: 0 0 10px;
        }

        .wcmb3-header p {
            color: #dbeafe;
            font-size: 13px;
            margin: 0;
        }

        .wcmb3-card {
            background: #fff;
            border: 1px solid #e8edf4;
            border-radius: 15px;
            padding: 24px;
            margin-bottom: 20px;
            box-shadow: 0 4px 18px rgba(15,23,42,.035);
        }

        .wcmb3-title {
            font-size: 16px;
            font-weight: 800;
            color: #1e293b;
            margin: 0 0 18px;
        }

        .wcmb3-stats {
            display: grid;
            grid-template-columns: repeat(3,1fr);
            gap: 14px;
        }

        .wcmb3-stat {
            padding: 19px;
            border-radius: 12px;
            border: 1px solid #edf1f6;
            background: #f8fafc;
        }

        .wcmb3-stat strong {
            display: block;
            font-size: 28px;
            color: #1d4ed8;
            margin-bottom: 5px;
        }

        .wcmb3-stat span {
            font-size: 12px;
            color: #64748b;
        }

        .wcmb3-buttons {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            margin-top: 22px;
        }

        .wcmb3-btn {
            border: 0;
            padding: 13px 21px;
            border-radius: 10px;
            font-size: 13px;
            font-weight: 700;
            cursor: pointer;
            transition: .2s;
        }

        .wcmb3-btn:hover:not(:disabled) {
            filter: brightness(.94);
            transform: translateY(-1px);
        }

        .wcmb3-btn:disabled {
            opacity: .4;
            cursor: not-allowed;
        }

        .wcmb3-scan {
            background: #e0e7ff;
            color: #1e40af;
        }

        .wcmb3-start {
            background: #2563eb;
            color: #fff;
        }

        .wcmb3-stop {
            background: #fee2e2;
            color: #b91c1c;
        }

        .wcmb3-resume {
            background: #dcfce7;
            color: #166534;
        }

        .wcmb3-progress-head {
            display: flex;
            justify-content: space-between;
            align-items: center;
            gap: 12px;
            margin-bottom: 15px;
        }

        .wcmb3-percent {
            font-size: 30px;
            font-weight: 800;
            color: #2563eb;
        }

        .wcmb3-progress {
            background: #e9eef5;
            height: 13px;
            border-radius: 30px;
            overflow: hidden;
        }

        .wcmb3-progress-bar {
            width: 0;
            height: 100%;
            background: linear-gradient(90deg,#2563eb,#60a5fa);
            border-radius: 30px;
            transition: width .3s ease;
        }

        .wcmb3-status {
            padding: 15px;
            background: #f8fafc;
            border: 1px solid #edf1f6;
            border-radius: 10px;
            margin-top: 18px;
            color: #475569;
            font-size: 13px;
            line-height: 2;
        }

        .wcmb3-preview {
            max-height: 350px;
            overflow-y: auto;
            background: #f8fafc;
            border: 1px solid #e8edf4;
            border-radius: 11px;
            padding: 12px;
        }

        .wcmb3-tree-item {
            font-size: 12px;
            padding: 8px;
            border-bottom: 1px solid #edf1f6;
            color: #475569;
        }

        .wcmb3-tree-item.root {
            color: #1d4ed8;
            font-weight: 800;
        }

        .wcmb3-log {
            height: 220px;
            overflow-y: auto;
            padding: 15px;
            background: #111827;
            color: #d1d5db;
            border-radius: 11px;
            font-size: 12px;
            line-height: 2.1;
        }

        .wcmb3-log .success {
            color: #86efac;
        }

        .wcmb3-log .error {
            color: #fca5a5;
        }

        .wcmb3-log .info {
            color: #93c5fd;
        }

        .wcmb3-link {
            display: inline-block;
            margin-top: 16px;
            color: #2563eb;
            text-decoration: none;
            font-weight: 700;
        }

        @media(max-width:600px) {

            .wcmb3-stats {
                grid-template-columns: 1fr;
            }

            .wcmb3-card {
                padding: 16px;
            }

            .wcmb3-buttons .wcmb3-btn {
                flex: 1 1 40%;
            }

            .wcmb3-header {
                padding: 22px;
            }

        }

        </style>


        <div class="wcmb3-header">

            <h1>مدیریت هوشمند فهرست دسته‌بندی محصولات</h1>

            <p>
                شناسایی دسته‌های موجود ووکامرس و ذخیره ساختار آن‌ها در فهرست وردپرس
            </p>

        </div>


        <div class="wcmb3-card">

            <h2 class="wcmb3-title">
                اطلاعات شناسایی
            </h2>

            <div class="wcmb3-stats">

                <div class="wcmb3-stat">
                    <strong id="wcmb3-total">0</strong>
                    <span>کل دسته‌بندی‌های ووکامرس</span>
                </div>

                <div class="wcmb3-stat">
                    <strong id="wcmb3-processed">0</strong>
                    <span>آیتم پردازش‌شده</span>
                </div>

                <div class="wcmb3-stat">
                    <strong id="wcmb3-created">0</strong>
                    <span>آیتم جدید فهرست</span>
                </div>

            </div>


            <div class="wcmb3-buttons">

                <button class="wcmb3-btn wcmb3-scan" id="wcmb3-scan">
                    ۱. شناسایی دسته‌بندی‌ها
                </button>

                <button class="wcmb3-btn wcmb3-start" id="wcmb3-start" disabled>
                    ۲. شروع ساخت فهرست
                </button>

                <button class="wcmb3-btn wcmb3-stop" id="wcmb3-stop" disabled>
                    توقف عملیات
                </button>

                <button class="wcmb3-btn wcmb3-resume" id="wcmb3-resume" disabled>
                    ادامه عملیات
                </button>

            </div>

            <div class="wcmb3-status" id="wcmb3-status">
                ابتدا دسته‌بندی‌های موجود ووکامرس را شناسایی کنید.
            </div>

        </div>


        <div class="wcmb3-card">

            <div class="wcmb3-progress-head">

                <div>
                    <h2 class="wcmb3-title" style="margin:0">
                        میزان پیشرفت عملیات
                    </h2>

                    <p style="color:#64748b;font-size:12px">
                        ساخت و ذخیره مرحله‌ای آیتم‌های فهرست
                    </p>
                </div>

                <div class="wcmb3-percent" id="wcmb3-percent">
                    0%
                </div>

            </div>

            <div class="wcmb3-progress">
                <div class="wcmb3-progress-bar" id="wcmb3-bar"></div>
            </div>

            <p id="wcmb3-current" style="font-size:13px;color:#64748b;margin-top:15px">
                دسته فعلی: هنوز شروع نشده است
            </p>

            <a href="#" id="wcmb3-menu-link" class="wcmb3-link" style="display:none">
                مشاهده فهرست دسته محصولات ←
            </a>

        </div>


        <div class="wcmb3-card">

            <h2 class="wcmb3-title">
                پیش‌نمایش ساختار دسته‌بندی‌ها
            </h2>

            <div id="wcmb3-preview" class="wcmb3-preview">
                <div style="color:#94a3b8;font-size:13px">
                    هنوز شناسایی انجام نشده است.
                </div>
            </div>

        </div>


        <div class="wcmb3-card">

            <h2 class="wcmb3-title">
                گزارش عملیات
            </h2>

            <div id="wcmb3-log" class="wcmb3-log">
                <div>سیستم آماده است.</div>
            </div>

        </div>

    </div>


    <script>
    jQuery(function($) {

        const config = <?php echo wp_json_encode($config); ?>;

        let total = 0;
        let offset = 0;

        let created = 0;
        let updated = 0;
        let skipped = 0;

        let running = false;
        let busy = false;
        let scanReady = false;

        const $scan = $('#wcmb3-scan');
        const $start = $('#wcmb3-start');
        const $stop = $('#wcmb3-stop');
        const $resume = $('#wcmb3-resume');


        function ajax(action, data = {}) {

            return $.ajax({
                url: config.ajax,
                type: 'POST',
                dataType: 'json',
                data: Object.assign({
                    action: action,
                    nonce: config.nonce
                }, data)
            });

        }


        function log(message, type = 'info') {

            $('<div>')
                .addClass(type)
                .text(message)
                .appendTo('#wcmb3-log');

            const box = $('#wcmb3-log')[0];

            box.scrollTop = box.scrollHeight;

        }


        function status(message) {
            $('#wcmb3-status').text(message);
        }


        function progress(value) {

            const percent = total > 0
                ? Math.round(value / total * 100)
                : 0;

            $('#wcmb3-total').text(total);
            $('#wcmb3-processed').text(value);
            $('#wcmb3-created').text(created);

            $('#wcmb3-percent').text(percent + '%');

            $('#wcmb3-bar').css('width', percent + '%');

        }


        function renderPreview(items) {

            const box = $('#wcmb3-preview').empty();

            if (!items || !items.length) {
                box.text('هیچ دسته‌بندی‌ای پیدا نشد.');
                return;
            }

            items.forEach(function(item) {

                $('<div>')
                    .addClass('wcmb3-tree-item')
                    .toggleClass('root', item.depth === 0)
                    .css(
                        'padding-right',
                        (12 + item.depth * 23) + 'px'
                    )
                    .text(item.name)
                    .appendTo(box);

            });

        }


        function buttons() {

            $scan.prop('disabled', running || busy);

            $start.prop(
                'disabled',
                !scanReady || running || busy || total === 0
            );

            $stop.prop('disabled', !running);

            $resume.prop(
                'disabled',
                !scanReady || running || busy || offset >= total
            );

        }


        function ajaxError(xhr) {

            if (xhr.responseJSON &&
                xhr.responseJSON.data &&
                xhr.responseJSON.data.message) {

                return xhr.responseJSON.data.message;
            }

            return 'خطا در ارتباط با سرور. گزارش خطا را بررسی کنید.';

        }


        /* SCAN */

        $scan.on('click', function() {

            if (running || busy) return;

            busy = true;
            scanReady = false;

            buttons();

            status('در حال شناسایی دسته‌های ووکامرس...');

            log('شروع شناسایی دسته‌بندی‌ها...');

            ajax('wcmb3_scan')

                .done(function(res) {

                    if (!res.success) {

                        status(res.data.message);
                        log(res.data.message, 'error');

                        return;
                    }

                    const data = res.data;

                    total = data.total;
                    offset = 0;

                    created = 0;
                    updated = 0;
                    skipped = 0;

                    scanReady = total > 0;

                    renderPreview(data.preview);
                    progress(0);

                    $('#wcmb3-menu-link').hide();

                    if (total === 0) {

                        status('هیچ دسته‌بندی‌ای در ووکامرس پیدا نشد.');

                        log('دسته‌ای برای ساخت فهرست وجود ندارد.', 'error');

                    } else {

                        status(
                            total + ' دسته شناسایی شد. آماده ساخت فهرست هستید.'
                        );

                        log(
                            total + ' دسته شناسایی شد.',
                            'success'
                        );

                        log(
                            'هیچ دسته‌بندی ووکامرس ایجاد یا تغییر داده نشده است.'
                        );

                    }

                })

                .fail(function(xhr) {

                    const message = ajaxError(xhr);

                    status(message);
                    log(message, 'error');

                })

                .always(function() {

                    busy = false;
                    buttons();

                });

        });


        /* START */

        $start.on('click', function() {

            if (!scanReady || running || busy) return;

            busy = true;
            buttons();

            status('در حال آماده‌سازی فهرست دسته محصولات...');

            ajax('wcmb3_start')

                .done(function(res) {

                    if (!res.success) {

                        status(res.data.message);
                        log(res.data.message, 'error');

                        return;
                    }

                    total = res.data.total;

                    offset = 0;

                    created = 0;
                    updated = 0;
                    skipped = 0;

                    progress(0);

                    running = true;

                    status('فهرست آماده شد. ساخت آیتم‌ها شروع می‌شود.');

                    log(
                        'فهرست دسته محصولات ایجاد یا شناسایی شد.',
                        'success'
                    );

                })

                .fail(function(xhr) {

                    const message = ajaxError(xhr);

                    status(message);
                    log(message, 'error');

                })

                .always(function() {

                    busy = false;
                    buttons();

                    if (running) {
                        setTimeout(processBatch, 150);
                    }

                });

        });


        /* PROCESS BATCH */

        function processBatch() {

            if (!running || busy) return;

            busy = true;
            buttons();

            let continueNext = false;

            ajax('wcmb3_process')

                .done(function(res) {

                    if (!res.success) {

                        running = false;

                        status(res.data.message);
                        log(res.data.message, 'error');

                        return;
                    }

                    const data = res.data;

                    offset = data.processed;

                    created = data.created;
                    updated = data.updated;
                    skipped = data.skipped;

                    progress(offset);

                    $('#wcmb3-current').text(
                        'دسته فعلی: ' + (data.current || 'پایان عملیات')
                    );

                    (data.messages || []).forEach(function(item) {

                        log(item.text, item.type);

                    });

                    if (data.done) {

                        running = false;

                        progress(total);

                        status(
                            'فهرست دسته محصولات با موفقیت ذخیره شد.'
                        );

                        log(
                            'عملیات ساخت فهرست تکمیل شد.',
                            'success'
                        );

                        if (data.menu_url) {

                            $('#wcmb3-menu-link')
                                .attr('href', data.menu_url)
                                .show();

                        }

                        return;
                    }

                    status(
                        'در حال ذخیره آیتم ' +
                        offset + ' از ' + total
                    );

                    continueNext = true;

                })

                .fail(function(xhr) {

                    running = false;

                    const message = ajaxError(xhr);

                    status(message);
                    log(message, 'error');

                })

                .always(function() {

                    busy = false;

                    buttons();

                    if (continueNext && running) {
                        setTimeout(processBatch, 150);
                    }

                });

        }


        /* STOP */

        $stop.on('click', function() {

            running = false;

            status(
                'عملیات متوقف شد. برای ادامه از همان مرحله استفاده کنید.'
            );

            log('توقف عملیات ثبت شد.');

            buttons();

        });


        /* RESUME */

        $resume.on('click', function() {

            if (running || busy || !scanReady) return;

            if (offset >= total) return;

            running = true;

            status('ادامه عملیات از مرحله قبلی...');

            log('ادامه عملیات از آیتم شماره ' + (offset + 1));

            buttons();

            processBatch();

        });


        /* RESTORE AFTER REFRESH */

        function restore() {

            ajax('wcmb3_status')

                .done(function(res) {

                    if (!res.success) return;

                    const data = res.data;

                    if (!data.has_scan) return;

                    scanReady = data.total > 0;
                    total = data.total;

                    renderPreview(data.preview);

                    if (data.run) {

                        offset = data.run.offset;

                        created = data.run.created;
                        updated = data.run.updated;
                        skipped = data.run.skipped;

                        progress(offset);

                        if (data.run.done) {

                            offset = total;

                            progress(total);

                            status('عملیات قبلی با موفقیت تکمیل شده است.');

                            $('#wcmb3-menu-link')
                                .attr('href', data.run.menu_url)
                                .show();

                        } else {

                            status(
                                'عملیات قبلی نیمه‌تمام است. امکان ادامه وجود دارد.'
                            );

                            log(
                                'وضعیت عملیات قبلی بازیابی شد.'
                            );

                        }

                    } else {

                        progress(0);

                        status(
                            total + ' دسته شناسایی شده است.'
                        );

                    }

                    buttons();

                });

        }

        restore();

    });
    </script>

    <?php
}


/* =====================================================
   5. AJAX SCAN
===================================================== */

add_action('wp_ajax_wcmb3_scan', function() {

    wcmb3_check_ajax();

    $items = wcmb3_scan_categories();

    if (is_wp_error($items)) {

        wp_send_json_error([
            'message' => $items->get_error_message()
        ]);
    }

    set_transient(
        wcmb3_key('scan'),
        $items,
        2 * DAY_IN_SECONDS
    );

    // A new scan starts a fresh operation
    delete_transient(wcmb3_key('run'));

    wp_send_json_success([

        'total' => count($items),

        'preview' => array_slice($items, 0, 200)

    ]);

});


/* =====================================================
   6. AJAX START - CREATE OR FIND MENU
===================================================== */

add_action('wp_ajax_wcmb3_start', function() {

    wcmb3_check_ajax();

    $items = get_transient(wcmb3_key('scan'));

    if (!is_array($items)) {

        wp_send_json_error([
            'message' => 'ابتدا شناسایی دسته‌بندی‌ها را اجرا کنید.'
        ]);
    }

    if (empty($items)) {

        wp_send_json_error([
            'message' => 'دسته‌بندی‌ای برای ساخت فهرست وجود ندارد.'
        ]);
    }

    // Find existing menu
    $menu = wcmb3_find_menu();

    // Create menu only after the Start button is clicked
    if (!$menu) {

        $menu_id = wp_create_nav_menu('دسته محصولات');

        if (is_wp_error($menu_id)) {

            wp_send_json_error([
                'message' => $menu_id->get_error_message()
            ]);
        }

    } else {

        $menu_id = (int) $menu->term_id;

    }

    // Collect available category IDs
    $valid_ids = [];

    foreach ($items as $item) {
        $valid_ids[(int) $item['term_id']] = true;
    }

    $existing_items = wp_get_nav_menu_items($menu_id);

    $item_map = [];
    $stale_ids = [];

    if ($existing_items) {

        foreach ($existing_items as $existing) {

            if (
                $existing->type !== 'taxonomy' ||
                $existing->object !== 'product_cat'
            ) {
                continue;
            }

            $term_id = (int) $existing->object_id;

            // Old/deleted categories are removed after successful completion
            if (!isset($valid_ids[$term_id])) {

                $stale_ids[] = (int) $existing->ID;

                continue;
            }

            // Keep first item, remove duplicates
            if (isset($item_map[$term_id])) {

                wp_delete_post(
                    $existing->ID,
                    true
                );

                continue;
            }

            $item_map[$term_id] = (int) $existing->ID;

        }
    }

    $state = [

        'menu_id' => (int) $menu_id,

        'items' => $items,

        'item_map' => $item_map,

        'stale_ids' => $stale_ids,

        'offset' => 0,

        'created' => 0,

        'updated' => 0,

        'skipped' => 0,

        'done' => false

    ];

    set_transient(
        wcmb3_key('run'),
        $state,
        2 * DAY_IN_SECONDS
    );

    wp_send_json_success([

        'menu_id' => $menu_id,

        'total' => count($items),

        'menu_name' => 'دسته محصولات'

    ]);

});


/* =====================================================
   7. AJAX PROCESS - SAVE MENU ITEMS
===================================================== */

add_action('wp_ajax_wcmb3_process', function() {

    wcmb3_check_ajax();

    $state = get_transient(wcmb3_key('run'));

    if (!is_array($state)) {

        wp_send_json_error([
            'message' => 'عملیاتی برای ادامه یافت نشد. دوباره شناسایی کنید.'
        ]);
    }

    $items = $state['items'];
    $total = count($items);
    $offset = (int) $state['offset'];

    $menu_id = (int) $state['menu_id'];

    if (!wp_get_nav_menu_object($menu_id)) {

        wp_send_json_error([
            'message' => 'فهرست مقصد در وردپرس پیدا نشد.'
        ]);
    }

    if ($offset >= $total) {

        $state['done'] = true;

        set_transient(
            wcmb3_key('run'),
            $state,
            2 * DAY_IN_SECONDS
        );

        wp_send_json_success([

            'processed' => $total,

            'created' => $state['created'],

            'updated' => $state['updated'],

            'skipped' => $state['skipped'],

            'done' => true,

            'messages' => [],

            'menu_url' => admin_url(
                'nav-menus.php?action=edit&menu=' . $menu_id
            )

        ]);
    }

    // Small batches reduce PHP execution time
    $batch_size = 5;

    $end = min($offset + $batch_size, $total);

    $messages = [];
    $current = '';

    for ($i = $offset; $i < $end; $i++) {

        $record = $items[$i];

        $term_id = (int) $record['term_id'];

        $current = $record['name'];

        // Verify category still exists
        $term = get_term($term_id, 'product_cat');

        if (!$term || is_wp_error($term)) {

            $state['skipped']++;

            $messages[] = [
                'text' => 'دسته دیگر وجود ندارد: ' . $record['name'],
                'type' => 'error'
            ];

            continue;
        }

        // Find actual parent menu item ID
        $parent_term_id = (int) $record['parent_id'];

        $parent_menu_id = 0;

        if (
            $parent_term_id > 0 &&
            isset($state['item_map'][$parent_term_id])
        ) {

            $parent_menu_id = (int) $state['item_map'][$parent_term_id];

        }

        $existing_id = isset($state['item_map'][$term_id])
            ? (int) $state['item_map'][$term_id]
            : 0;

        // Create or update WordPress navigation menu item
        $result = wp_update_nav_menu_item(
            $menu_id,
            $existing_id,
            [

                'menu-item-title' =>
                    $term->name,

                'menu-item-object' =>
                    'product_cat',

                'menu-item-object-id' =>
                    $term_id,

                'menu-item-type' =>
                    'taxonomy',

                'menu-item-status' =>
                    'publish',

                'menu-item-parent-id' =>
                    $parent_menu_id,

                'menu-item-position' =>
                    $i + 1

            ]
        );

        if (is_wp_error($result) || !$result) {

            $state['skipped']++;

            $messages[] = [
                'text' => 'خطا در ذخیره آیتم: ' . $term->name,
                'type' => 'error'
            ];

            continue;
        }

        $state['item_map'][$term_id] = (int) $result;

        if ($existing_id) {

            $state['updated']++;

            $messages[] = [
                'text' => 'به‌روزرسانی شد: ' . $term->name,
                'type' => 'info'
            ];

        } else {

            $state['created']++;

            $messages[] = [
                'text' => 'ایجاد و ذخیره شد: ' . $term->name,
                'type' => 'success'
            ];

        }

    }

    $state['offset'] = $end;

    $state['done'] = ($end >= $total);

    // Save progress after every batch
    set_transient(
        wcmb3_key('run'),
        $state,
        2 * DAY_IN_SECONDS
    );

    // Remove obsolete product category items only after successful finish
    if ($state['done']) {

        foreach ($state['stale_ids'] as $stale_id) {

            wp_delete_post(
                (int) $stale_id,
                true
            );

        }

        clean_post_cache($menu_id);

    }

    $menu_url = admin_url(
        'nav-menus.php?action=edit&menu=' . $menu_id
    );

    wp_send_json_success([

        'processed' => $end,

        'total' => $total,

        'created' => $state['created'],

        'updated' => $state['updated'],

        'skipped' => $state['skipped'],

        'current' => $current,

        'done' => $state['done'],

        'menu_url' => $menu_url,

        'messages' => $messages

    ]);

});


/* =====================================================
   8. AJAX RESTORE DASHBOARD STATE
===================================================== */

add_action('wp_ajax_wcmb3_status', function() {

    wcmb3_check_ajax();

    $scan = get_transient(wcmb3_key('scan'));

    $state = get_transient(wcmb3_key('run'));

    $response = [

        'has_scan' => is_array($scan),

        'total' => is_array($scan)
            ? count($scan)
            : 0,

        'preview' => is_array($scan)
            ? array_slice($scan, 0, 200)
            : [],

        'run' => null

    ];

    if (is_array($state)) {

        $response['run'] = [

            'offset' => (int) $state['offset'],

            'created' => (int) $state['created'],

            'updated' => (int) $state['updated'],

            'skipped' => (int) $state['skipped'],

            'done' => (bool) $state['done'],

            'menu_url' => admin_url(
                'nav-menus.php?action=edit&menu=' .
                (int) $state['menu_id']
            )

        ];
    }

    wp_send_json_success($response);

});

سازنده هوشمند فهرست دسته‌بندی محصولات ووکامرس

🛍️ مدیریت دسته‌بندی محصولات یکی از بخش‌های مهم هر فروشگاه اینترنتی است. زمانی که تعداد دسته‌ها و زیرمجموعه‌های محصولات افزایش پیدا می‌کند، ایجاد دستی فهرست‌های ناوبری در وردپرس می‌تواند زمان‌بر و دشوار باشد. افزونه سازنده هوشمند فهرست دسته‌بندی محصولات ووکامرس، راهکاری کاربردی برای شناسایی خودکار دسته‌بندی‌های موجود و انتقال ساختار آن‌ها به فهرست‌های وردپرس است.

این ابزار بدون ایجاد دسته‌بندی جدید یا تغییر اطلاعات محصولات، تمام دسته‌های ثبت‌شده در ووکامرس را شناسایی می‌کند و امکان ساخت یک فهرست کامل با نام «دسته محصولات» را فراهم می‌سازد.

✨ قابلیت‌های اصلی افزونه

🔍 ۱. شناسایی خودکار دسته‌بندی‌ها

تمام دسته‌بندی‌های موجود در ووکامرس، شامل دسته‌های اصلی، زیرمجموعه‌ها و دسته‌های بدون محصول شناسایی می‌شوند. اطلاعات هر دسته شامل عنوان، شناسه، نامک و ارتباط آن با دسته والد بررسی می‌شود.

📁 ۲. حفظ ساختار سلسله‌مراتبی

یکی از مهم‌ترین ویژگی‌های این ابزار، حفظ دقیق ارتباط والد و فرزند است. اگر یک دسته دارای چندین زیرمجموعه باشد، ساختار آن‌ها هنگام انتقال به فهرست وردپرس نیز حفظ خواهد شد.

⚡ ۳. ساخت خودکار فهرست محصولات

پس از شناسایی دسته‌بندی‌ها، با انتخاب گزینه شروع، فهرستی با نام «دسته محصولات» در بخش نمایش و مدیریت فهرست‌های وردپرس ایجاد می‌شود. تمام دسته‌های شناسایی‌شده به‌عنوان آیتم‌های واقعی فهرست به آن اضافه خواهند شد.

📊 ۴. نوار پیشرفت هوشمند

فرایند ساخت فهرست به‌صورت مرحله‌ای و با درخواست‌های AJAX انجام می‌شود. میزان پیشرفت عملیات از صفر تا صد درصد نمایش داده شده و تعداد آیتم‌های پردازش‌شده و ساخته‌شده قابل مشاهده است.

⏸️ ۵. توقف و ادامه عملیات

کاربر می‌تواند در هر مرحله عملیات را متوقف کند و در صورت نیاز، از همان مرحله قبلی ادامه دهد. وضعیت پیشرفت نیز برای بازیابی پس از بارگذاری مجدد صفحه ذخیره می‌شود.

🔄 ۶. جلوگیری از آیتم‌های تکراری

در صورت اجرای مجدد عملیات، آیتم‌های موجود شناسایی و به‌روزرسانی می‌شوند تا از ایجاد موارد تکراری جلوگیری شود. همچنین آیتم‌های مربوط به دسته‌هایی که دیگر وجود ندارند، پس از تکمیل موفق عملیات از فهرست اختصاصی حذف می‌شوند.

📝 ۷. گزارش لحظه‌ای عملیات

تمام مراحل شامل ایجاد آیتم، به‌روزرسانی، موارد ردشده و خطاهای احتمالی در بخش گزارش نمایش داده می‌شوند تا مدیریت و بررسی عملیات ساده‌تر باشد.

🎯 مزایای استفاده از ابزار

  • کاهش زمان ساخت فهرست‌های فروشگاهی
  • حذف نیاز به افزودن دستی دسته‌ها
  • حفظ ساختار دقیق دسته‌بندی‌ها
  • مدیریت آسان فروشگاه‌های دارای دسته‌بندی زیاد
  • سازگاری با ساختار استاندارد دسته‌بندی ووکامرس
  • عدم وابستگی به قالب خاص
  • پنل مدیریتی ساده و کاربردی

⚙️ نحوه استفاده

پس از نصب و فعال‌سازی اسنیپت، وارد بخش محصولات و گزینه «سازنده فهرست دسته‌ها» شوید. ابتدا دسته‌بندی‌های موجود را شناسایی کنید، ساختار آن‌ها را بررسی کرده و سپس با انتخاب شروع ساخت فهرست، تمام دسته‌ها را به فهرست «دسته محصولات» منتقل کنید.

نکته مهم: این ابزار فقط فهرست ناوبری وردپرس را ایجاد و مدیریت می‌کند و هیچ دسته‌بندی جدیدی در ووکامرس نمی‌سازد یا اطلاعات محصولات را تغییر نمی‌دهد. اتصال فهرست به هدر یا فوتر نیز از طریق تنظیمات جایگاه فهرست قالب انجام می‌شود.