64 lines
1.6 KiB
PHP
64 lines
1.6 KiB
PHP
|
|
<?php
|
||
|
|
|
||
|
|
function get_categories_from_menu_exact_order($menu_name) {
|
||
|
|
|
||
|
|
$cache_key = 'categories_from_menu_' . $menu_name;
|
||
|
|
$cache_group = 'menu_categories';
|
||
|
|
|
||
|
|
// Попытка получить кэш
|
||
|
|
$cached = wp_cache_get($cache_key, $cache_group);
|
||
|
|
if ($cached !== false) {
|
||
|
|
return $cached;
|
||
|
|
}
|
||
|
|
|
||
|
|
// Получение пунктов меню
|
||
|
|
$menu_items = wp_get_nav_menu_items($menu_name);
|
||
|
|
if (!$menu_items) return [];
|
||
|
|
|
||
|
|
$category_ids = [];
|
||
|
|
foreach ($menu_items as $item) {
|
||
|
|
if ($item->object === 'category') {
|
||
|
|
$category_ids[] = (int) $item->object_id;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
if (empty($category_ids)) return [];
|
||
|
|
|
||
|
|
// Получение категорий
|
||
|
|
$terms = get_terms([
|
||
|
|
'taxonomy' => 'category',
|
||
|
|
'include' => $category_ids,
|
||
|
|
'hide_empty' => false,
|
||
|
|
]);
|
||
|
|
|
||
|
|
// Индексация по ID
|
||
|
|
$indexed = [];
|
||
|
|
foreach ($terms as $term) {
|
||
|
|
$indexed[$term->term_id] = $term;
|
||
|
|
}
|
||
|
|
|
||
|
|
// Сортировка по порядку в меню
|
||
|
|
$ordered = [];
|
||
|
|
foreach ($category_ids as $id) {
|
||
|
|
if (isset($indexed[$id])) {
|
||
|
|
$ordered[] = $indexed[$id];
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
// Кэшируем результат
|
||
|
|
wp_cache_set($cache_key, $ordered, $cache_group);
|
||
|
|
|
||
|
|
return $ordered;
|
||
|
|
|
||
|
|
}
|
||
|
|
|
||
|
|
//очищаем кеш при редактировании меню
|
||
|
|
add_action('wp_update_nav_menu', function($menu_id) {
|
||
|
|
$menu = wp_get_nav_menu_object($menu_id);
|
||
|
|
if ($menu && $menu->slug === 'rubrics') {
|
||
|
|
wp_cache_delete('categories_from_menu_rubrics', 'menu_categories');
|
||
|
|
}
|
||
|
|
});
|
||
|
|
|
||
|
|
|