| |
| <?php
|
| if( function_exists('acf_add_options_page') ) {
|
| acf_add_options_page();
|
| }
|
|
|
|
|
| add_action('acf/init', function() {
|
| if( function_exists('acf_add_local_field_group') ) {
|
|
|
| acf_add_local_field_group(array(
|
| 'key' => 'group_menu_json_import',
|
| 'title' => 'Menu Import',
|
| 'fields' => array(
|
| array(
|
| 'key' => 'field_menu_json',
|
| 'label' => 'Menu JSON',
|
| 'name' => 'menu_json',
|
| 'type' => class_exists('ACF_Field_Code') ? 'code' : 'textarea',
|
| 'instructions' => 'Paste your JSON menu structure here.',
|
| 'rows' => 10,
|
| 'new_lines' => '',
|
| ),
|
| ),
|
| 'location' => array(
|
| array(
|
| array(
|
| 'param' => 'options_page',
|
| 'operator' => '==',
|
| 'value' => 'acf-options',
|
| ),
|
| ),
|
| ),
|
| ));
|
| }
|
| });
|
|
|
|
|
| add_action('acf/save_post', 'import_menu_from_acf_json', 20);
|
| function import_menu_from_acf_json($post_id) {
|
|
|
| if ($post_id !== 'options') return;
|
|
|
| $json_string = get_field('menu_json', 'option');
|
| if (!$json_string) return;
|
|
|
| $data = json_decode($json_string, true);
|
| if (json_last_error() !== JSON_ERROR_NONE || !is_array($data)) {
|
| error_log('Invalid JSON in Menu JSON ACF field.');
|
| return;
|
| }
|
|
|
| if (!isset($data['menu_name'], $data['menu_items']) || !is_array($data['menu_items'])) return;
|
|
|
| $menu = wp_get_nav_menu_object($data['menu_name']);
|
| if (!$menu) {
|
| $menu_id = wp_create_nav_menu($data['menu_name']);
|
| } else {
|
| $menu_id = $menu->term_id;
|
| }
|
|
|
|
|
| $items = wp_get_nav_menu_items($menu_id);
|
| if ($items) {
|
| foreach ($items as $item) {
|
| wp_delete_post($item->ID, true);
|
| }
|
| }
|
|
|
| $item_ids = [];
|
| foreach ($data['menu_items'] as $item) {
|
| $parent_id = 0;
|
| if (!empty($item['menu_item_parent']) && isset($item_ids[$item['menu_item_parent']])) {
|
| $parent_id = $item_ids[$item['menu_item_parent']];
|
| }
|
|
|
| $item_id = wp_update_nav_menu_item($menu_id, 0, [
|
| 'menu-item-title' => $item['title'],
|
| 'menu-item-url' => $item['url'],
|
| 'menu-item-status' => 'publish',
|
| 'menu-item-parent-id' => $parent_id,
|
| ]);
|
|
|
| $item_ids[$item['title']] = $item_id;
|
| }
|
|
|
|
|
| $locations = get_theme_mod('nav_menu_locations');
|
| $locations['primary'] = $menu_id;
|
| set_theme_mod('nav_menu_locations', $locations);
|
| }
|
|
|
| |
| |
Comments