123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563
/**
* 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);
});