Menus), which wp_nav_menu() renders. * * Who: people whose own role may edit menus (edit_theme_options, normally * Administrators), through their connection; AI Agent users can't. When: * the site mode must be "Publish and edit live posts", since menu changes * are live immediately. Safety: every change set is all-or-nothing, and the * menu is snapshotted before it (WordPress keeps no menu history), so * restore-menu can undo it. * * @package Acadium_Agent_Publisher */ defined( 'ABSPATH' ) || exit; final class Agent_Publisher_Menus { const SNAPSHOTS = 'agent_publisher_menu_snapshots'; const MAX_SNAPSHOTS = 10; public static function init() { add_action( 'wp_abilities_api_init', array( __CLASS__, 'register' ) ); } private static function meta( $readonly, $destructive, $idempotent ) { return array( 'annotations' => array( 'readonly' => $readonly, 'destructive' => $destructive, 'idempotent' => $idempotent ), 'public' => true, 'show_in_rest' => true, 'mcp' => array( 'public' => true ), ); } public static function permission( $write ) { if ( Agent_Publisher_Policy::is_agent_user() || ! current_user_can( 'edit_theme_options' ) ) { return new WP_Error( 'agent_publisher_role', 'Your WordPress role can\'t edit menus (Administrators can), so Claude can\'t change them for you.', array( 'status' => 403 ) ); } if ( $write && ! Agent_Publisher_Policy::allows( 'publish_edit' ) ) { return Agent_Publisher_Policy::not_allowed( 'change menus', 'publish_edit' ); } return true; } public static function register() { $link = array( 'page_id' => array( 'type' => 'integer', 'description' => 'Link to this page (find it with find-posts). The menu follows the page if its URL changes.' ), 'post_id' => array( 'type' => 'integer', 'description' => 'Link to this post.' ), 'category_id' => array( 'type' => 'integer', 'description' => 'Link to this category archive (see list-terms).' ), 'url' => array( 'type' => 'string', 'description' => 'Custom link (http/https, or a path like /pricing/).' ), ); wp_register_ability( 'agent-publisher/list-menus', array( 'label' => __( 'List menus', 'acadium-agent-publisher' ), 'description' => 'Lists the site\'s navigation menus with their items (id, title, url, what they link to, parent item, order, new tab), and the theme\'s menu locations (e.g. header, footer) with the menu shown in each. Call it before update-menu.', 'category' => Agent_Publisher_Abilities::CATEGORY, 'input_schema' => array( 'type' => 'object', 'properties' => new stdClass(), 'additionalProperties' => false, 'default' => array(), ), 'output_schema' => array( 'type' => 'object', 'properties' => array( 'menus' => array( 'type' => 'array', 'items' => array( 'type' => 'object' ) ), 'locations' => array( 'type' => 'object', 'description' => 'Theme menu locations: slug => { label, menu_id }.' ), 'block_theme' => array( 'type' => 'boolean', 'description' => 'Block themes show Navigation blocks, not these menus.' ), ), ), 'execute_callback' => array( __CLASS__, 'list_menus' ), 'permission_callback' => function () { return self::permission( false ); }, 'meta' => self::meta( true, false, true ), ) ); wp_register_ability( 'agent-publisher/create-menu', array( 'label' => __( 'Create a menu', 'acadium-agent-publisher' ), 'description' => 'Creates an empty navigation menu, optionally shown in a theme location (see list-menus > locations). Then add items with update-menu.', 'category' => Agent_Publisher_Abilities::CATEGORY, 'input_schema' => array( 'type' => 'object', 'properties' => array( 'name' => array( 'type' => 'string' ), 'location' => array( 'type' => 'string', 'description' => 'Optional theme location slug to show it in (replaces the menu shown there).' ), ), 'required' => array( 'name' ), 'additionalProperties' => false, ), 'output_schema' => array( 'type' => 'object' ), 'execute_callback' => array( __CLASS__, 'create_menu' ), 'permission_callback' => function () { return self::permission( true ); }, 'meta' => self::meta( false, false, false ), ) ); wp_register_ability( 'agent-publisher/update-menu', array( 'label' => __( 'Change a menu', 'acadium-agent-publisher' ), 'description' => 'Changes a navigation menu\'s items with a list of changes, applied in order, all or nothing (if one fails, none are kept). Actions: "add" (a link to page_id, post_id, category_id or url; optional title, parent, after, new_tab), "update" (item_id plus title, a new link target, or new_tab), "move" (item_id plus parent and/or after), "remove" (item_id; its sub-items move up a level). parent is a menu item id (0 for top level); after is the item id to place it after (omit for the end). Changes are live immediately. The returned snapshot_id undoes them with restore-menu.', 'category' => Agent_Publisher_Abilities::CATEGORY, 'input_schema' => array( 'type' => 'object', 'properties' => array( 'menu_id' => array( 'type' => 'integer', 'description' => 'From list-menus.' ), 'changes' => array( 'type' => 'array', 'minItems' => 1, 'items' => array( 'type' => 'object', 'properties' => array_merge( array( 'action' => array( 'type' => 'string', 'enum' => array( 'add', 'update', 'move', 'remove' ) ), 'item_id' => array( 'type' => 'integer', 'description' => 'Menu item to update, move or remove.' ), 'title' => array( 'type' => 'string', 'description' => 'Link text. For page/post/category links, omit to use their title.' ), 'parent' => array( 'type' => 'integer', 'description' => 'Parent menu item id (0 = top level).' ), 'after' => array( 'type' => 'integer', 'description' => 'Place it right after this menu item.' ), 'new_tab' => array( 'type' => 'boolean' ), ), $link ), 'required' => array( 'action' ), 'additionalProperties' => false, ), ), ), 'required' => array( 'menu_id', 'changes' ), 'additionalProperties' => false, ), 'output_schema' => array( 'type' => 'object' ), 'execute_callback' => array( __CLASS__, 'update_menu' ), 'permission_callback' => function () { return self::permission( true ); }, 'meta' => self::meta( false, true, false ), ) ); wp_register_ability( 'agent-publisher/restore-menu', array( 'label' => __( 'Restore a menu', 'acadium-agent-publisher' ), 'description' => 'Puts a menu back exactly as it was before an update-menu call (its snapshot_id; list-menus > snapshots lists the last ' . self::MAX_SNAPSHOTS . '). Use it to undo menu changes.', 'category' => Agent_Publisher_Abilities::CATEGORY, 'input_schema' => array( 'type' => 'object', 'properties' => array( 'menu_id' => array( 'type' => 'integer' ), 'snapshot_id' => array( 'type' => 'string' ), ), 'required' => array( 'menu_id', 'snapshot_id' ), 'additionalProperties' => false, ), 'output_schema' => array( 'type' => 'object' ), 'execute_callback' => array( __CLASS__, 'restore_menu' ), 'permission_callback' => function () { return self::permission( true ); }, 'meta' => self::meta( false, true, false ), ) ); } /* ------------------------------------------------------------------ */ /* Reading */ /* ------------------------------------------------------------------ */ private static function items( $menu_id ) { $items = wp_get_nav_menu_items( $menu_id, array( 'update_post_term_cache' => false ) ); return is_array( $items ) ? $items : array(); } private static function describe( $item ) { return array( 'id' => (int) $item->ID, 'title' => html_entity_decode( (string) $item->title ), 'url' => (string) $item->url, 'links_to' => 'custom' === $item->type ? 'custom' : $item->object . ':' . (int) $item->object_id, 'parent' => (int) $item->menu_item_parent, 'order' => (int) $item->menu_order, 'new_tab' => '_blank' === $item->target, ); } public static function list_menus() { $assigned = get_nav_menu_locations(); $locations = array(); foreach ( get_registered_nav_menus() as $slug => $label ) { $locations[ $slug ] = array( 'label' => $label, 'menu_id' => (int) ( $assigned[ $slug ] ?? 0 ) ); } $snapshots = (array) get_option( self::SNAPSHOTS, array() ); $menus = array(); foreach ( wp_get_nav_menus() as $menu ) { $menus[] = array( 'id' => (int) $menu->term_id, 'name' => $menu->name, 'locations' => array_keys( array_filter( $assigned, function ( $id ) use ( $menu ) { return (int) $id === (int) $menu->term_id; } ) ), 'items' => array_map( array( __CLASS__, 'describe' ), self::items( $menu->term_id ) ), 'snapshots' => array_map( function ( $s ) { return array( 'snapshot_id' => $s['id'], 'date' => gmdate( 'c', $s['time'] ) ); }, array_reverse( (array) ( $snapshots[ $menu->term_id ] ?? array() ) ) ), ); } return array( 'menus' => $menus, 'locations' => (object) $locations, 'block_theme' => function_exists( 'wp_is_block_theme' ) && wp_is_block_theme(), ); } /* ------------------------------------------------------------------ */ /* Writing */ /* ------------------------------------------------------------------ */ public static function create_menu( $input ) { $name = sanitize_text_field( $input['name'] ); if ( '' === $name ) { return new WP_Error( 'agent_publisher_bad_field', 'name is required.', array( 'status' => 400 ) ); } $location = isset( $input['location'] ) ? sanitize_key( $input['location'] ) : ''; if ( '' !== $location && ! array_key_exists( $location, get_registered_nav_menus() ) ) { return new WP_Error( 'agent_publisher_bad_location', 'Unknown menu location. Available: ' . implode( ', ', array_keys( get_registered_nav_menus() ) ) . '.', array( 'status' => 400 ) ); } $id = wp_create_nav_menu( $name ); if ( is_wp_error( $id ) ) { return $id; } if ( '' !== $location ) { $locations = get_nav_menu_locations(); $locations[ $location ] = (int) $id; set_theme_mod( 'nav_menu_locations', $locations ); } Agent_Publisher_Policy::log( 'menu', 0, 'Created menu "' . $name . '"' ); return array( 'id' => (int) $id, 'name' => $name, 'location' => $location ); } /** Every field of an existing item, as wp_update_nav_menu_item() expects (it doesn't merge with what's stored). */ private static function args( $item ) { return array( 'menu-item-object-id' => (int) $item->object_id, 'menu-item-object' => (string) $item->object, 'menu-item-parent-id' => (int) $item->menu_item_parent, 'menu-item-position' => (int) $item->menu_order, 'menu-item-type' => (string) $item->type, 'menu-item-title' => (string) $item->post_title, 'menu-item-url' => (string) $item->url, 'menu-item-description' => (string) $item->description, 'menu-item-attr-title' => (string) $item->attr_title, 'menu-item-target' => (string) $item->target, 'menu-item-classes' => implode( ' ', array_filter( (array) $item->classes ) ), 'menu-item-xfn' => (string) $item->xfn, 'menu-item-status' => 'publish', ); } /** The link part of a change, as menu item args, or an error. */ private static function link_args( array $change, $required ) { $targets = array_filter( array_intersect_key( $change, array_flip( array( 'page_id', 'post_id', 'category_id', 'url' ) ) ), function ( $v ) { return null !== $v && '' !== $v; } ); if ( count( $targets ) > 1 ) { return new WP_Error( 'agent_publisher_bad_link', 'Give one of page_id, post_id, category_id or url.', array( 'status' => 400 ) ); } if ( ! $targets ) { return $required ? new WP_Error( 'agent_publisher_bad_link', 'add needs a link: page_id, post_id, category_id or url.', array( 'status' => 400 ) ) : array(); } $key = key( $targets ); $value = current( $targets ); if ( 'url' === $key ) { $url = esc_url_raw( (string) $value, array( 'http', 'https' ) ); if ( '' === $url && 0 === strpos( (string) $value, '/' ) ) { $url = esc_url_raw( home_url( (string) $value ) ); } if ( '' === $url ) { return new WP_Error( 'agent_publisher_bad_link', 'url must be http(s) or a path like /pricing/.', array( 'status' => 400 ) ); } return array( 'menu-item-type' => 'custom', 'menu-item-object' => 'custom', 'menu-item-object-id' => 0, 'menu-item-url' => $url ); } if ( 'category_id' === $key ) { $term = get_term( (int) $value, 'category' ); if ( ! $term || is_wp_error( $term ) ) { return new WP_Error( 'agent_publisher_bad_link', "Category $value does not exist.", array( 'status' => 400 ) ); } return array( 'menu-item-type' => 'taxonomy', 'menu-item-object' => 'category', 'menu-item-object-id' => (int) $term->term_id, 'menu-item-url' => '' ); } $type = 'page_id' === $key ? 'page' : 'post'; $post = get_post( (int) $value ); if ( ! $post || $post->post_type !== $type || 'trash' === $post->post_status ) { return new WP_Error( 'agent_publisher_bad_link', sprintf( '%1$s %2$d does not exist.', ucfirst( $type ), (int) $value ), array( 'status' => 400 ) ); } return array( 'menu-item-type' => 'post_type', 'menu-item-object' => $type, 'menu-item-object-id' => (int) $post->ID, 'menu-item-url' => '' ); } public static function update_menu( $input ) { $menu = wp_get_nav_menu_object( (int) $input['menu_id'] ); if ( ! $menu ) { return new WP_Error( 'agent_publisher_bad_menu', 'No such menu. See list-menus.', array( 'status' => 404 ) ); } $snapshot = self::snapshot( $menu->term_id ); $result = self::apply_changes( $menu->term_id, (array) $input['changes'] ); if ( is_wp_error( $result ) ) { self::put_back( $menu->term_id, $snapshot['items'] ); // All or nothing. self::drop_snapshot( $menu->term_id, $snapshot['id'] ); return new WP_Error( $result->get_error_code(), $result->get_error_message() . ' No changes were kept.', $result->get_error_data() ); } Agent_Publisher_Policy::log( 'menu', 0, sprintf( 'Menu "%1$s": %2$d change(s)', $menu->name, count( (array) $input['changes'] ) ) ); return array( 'menu_id' => (int) $menu->term_id, 'snapshot_id' => $snapshot['id'], 'items' => array_map( array( __CLASS__, 'describe' ), self::items( $menu->term_id ) ), ); } private static function apply_changes( $menu_id, array $changes ) { foreach ( array_values( $changes ) as $n => $change ) { $label = sprintf( 'Change %d (%s): ', $n + 1, $change['action'] ?? '?' ); $by_id = array(); foreach ( self::items( $menu_id ) as $item ) { $by_id[ (int) $item->ID ] = $item; } foreach ( array( 'item_id', 'parent', 'after' ) as $ref ) { if ( ! empty( $change[ $ref ] ) && ! isset( $by_id[ (int) $change[ $ref ] ] ) ) { return new WP_Error( 'agent_publisher_bad_item', $label . "menu item {$change[ $ref ]} ($ref) is not in this menu.", array( 'status' => 400 ) ); } } $action = $change['action']; if ( 'add' !== $action && empty( $change['item_id'] ) ) { return new WP_Error( 'agent_publisher_bad_item', $label . 'item_id is required.', array( 'status' => 400 ) ); } if ( 'remove' === $action ) { $item = $by_id[ (int) $change['item_id'] ]; foreach ( $by_id as $child ) { // Sub-items move up a level. if ( (int) $child->menu_item_parent === (int) $item->ID ) { $args = self::args( $child ); $args['menu-item-parent-id'] = (int) $item->menu_item_parent; wp_update_nav_menu_item( $menu_id, $child->ID, $args ); } } wp_delete_post( $item->ID, true ); continue; } $link = self::link_args( $change, 'add' === $action ); if ( is_wp_error( $link ) ) { return new WP_Error( $link->get_error_code(), $label . $link->get_error_message(), $link->get_error_data() ); } $args = 'add' === $action ? array( 'menu-item-status' => 'publish', 'menu-item-parent-id' => 0, 'menu-item-position' => 0 ) : self::args( $by_id[ (int) $change['item_id'] ] ); $args = array_merge( $args, $link ); if ( isset( $change['title'] ) ) { $args['menu-item-title'] = sanitize_text_field( $change['title'] ); } if ( isset( $change['new_tab'] ) ) { $args['menu-item-target'] = $change['new_tab'] ? '_blank' : ''; } if ( isset( $change['parent'] ) ) { if ( ! empty( $change['item_id'] ) && (int) $change['parent'] === (int) $change['item_id'] ) { return new WP_Error( 'agent_publisher_bad_item', $label . 'an item can\'t be its own parent.', array( 'status' => 400 ) ); } $args['menu-item-parent-id'] = (int) $change['parent']; } $id = wp_update_nav_menu_item( $menu_id, 'add' === $action ? 0 : (int) $change['item_id'], $args ); if ( is_wp_error( $id ) ) { return new WP_Error( $id->get_error_code(), $label . $id->get_error_message(), array( 'status' => 400 ) ); } if ( 'add' === $action || isset( $change['after'] ) || 'move' === $action ) { self::reorder( $menu_id, (int) $id, isset( $change['after'] ) ? (int) $change['after'] : null ); } } return true; } /** Put $id right after $after (or last), renumbering the menu's items 1..n. */ private static function reorder( $menu_id, $id, $after ) { $ids = array_values( array_diff( array_map( function ( $i ) { return (int) $i->ID; }, self::items( $menu_id ) ), array( $id ) ) ); $at = null === $after ? false : array_search( $after, $ids, true ); array_splice( $ids, false === $at ? count( $ids ) : $at + 1, 0, array( $id ) ); foreach ( $ids as $n => $item_id ) { wp_update_post( array( 'ID' => $item_id, 'menu_order' => $n + 1 ) ); } } /* ------------------------------------------------------------------ */ /* Snapshots (undo) */ /* ------------------------------------------------------------------ */ private static function snapshot( $menu_id ) { $items = array(); foreach ( self::items( $menu_id ) as $item ) { $items[] = array( 'old_id' => (int) $item->ID ) + self::args( $item ); } $snapshot = array( 'id' => wp_generate_password( 12, false ), 'time' => time(), 'user' => get_current_user_id(), 'items' => $items ); $all = (array) get_option( self::SNAPSHOTS, array() ); $list = (array) ( $all[ $menu_id ] ?? array() ); $list[] = $snapshot; $all[ $menu_id ] = array_slice( $list, -self::MAX_SNAPSHOTS ); update_option( self::SNAPSHOTS, $all, false ); return $snapshot; } private static function drop_snapshot( $menu_id, $snapshot_id ) { $all = (array) get_option( self::SNAPSHOTS, array() ); $all[ $menu_id ] = array_values( array_filter( (array) ( $all[ $menu_id ] ?? array() ), function ( $s ) use ( $snapshot_id ) { return $s['id'] !== $snapshot_id; } ) ); update_option( self::SNAPSHOTS, $all, false ); } /** Replace the menu's items with a snapshot's (new item IDs; parents remapped). */ private static function put_back( $menu_id, array $items ) { foreach ( self::items( $menu_id ) as $item ) { wp_delete_post( $item->ID, true ); } $map = array( 0 => 0 ); $todo = $items; for ( $pass = 0; $todo && $pass < 50; $pass++ ) { foreach ( $todo as $k => $saved ) { $parent = (int) $saved['menu-item-parent-id']; if ( ! isset( $map[ $parent ] ) && in_array( $parent, array_column( $items, 'old_id' ), true ) ) { continue; // Parent not recreated yet. } $args = $saved; $args['menu-item-parent-id'] = $map[ $parent ] ?? 0; unset( $args['old_id'] ); $map[ (int) $saved['old_id'] ] = (int) wp_update_nav_menu_item( $menu_id, 0, $args ); unset( $todo[ $k ] ); } } } public static function restore_menu( $input ) { $menu = wp_get_nav_menu_object( (int) $input['menu_id'] ); $all = (array) get_option( self::SNAPSHOTS, array() ); $snap = null; foreach ( (array) ( $all[ (int) $input['menu_id'] ] ?? array() ) as $s ) { if ( hash_equals( (string) $s['id'], (string) $input['snapshot_id'] ) ) { $snap = $s; } } if ( ! $menu || ! $snap ) { return new WP_Error( 'agent_publisher_bad_snapshot', 'No such menu snapshot. See list-menus > snapshots.', array( 'status' => 404 ) ); } $before = self::snapshot( $menu->term_id ); // Restoring can be undone too. self::put_back( $menu->term_id, $snap['items'] ); Agent_Publisher_Policy::log( 'menu', 0, sprintf( 'Menu "%s": restored', $menu->name ) ); return array( 'menu_id' => (int) $menu->term_id, 'snapshot_id' => $before['id'], 'items' => array_map( array( __CLASS__, 'describe' ), self::items( $menu->term_id ) ), ); } }