3 * WordPress Customize Nav Menus classes
6 * @subpackage Customize
11 * Customize Nav Menus class.
13 * Implements menu management in the Customizer.
17 * @see WP_Customize_Manager
19 final class WP_Customize_Nav_Menus {
22 * WP_Customize_Manager instance.
26 * @var WP_Customize_Manager
37 public $previewed_menus;
45 * @param object $manager An instance of the WP_Customize_Manager class.
47 public function __construct( $manager ) {
48 $this->previewed_menus = array();
49 $this->manager = $manager;
51 // Skip useless hooks when the user can't manage nav menus anyway.
52 if ( ! current_user_can( 'edit_theme_options' ) ) {
56 add_filter( 'customize_refresh_nonces', array( $this, 'filter_nonces' ) );
57 add_action( 'wp_ajax_load-available-menu-items-customizer', array( $this, 'ajax_load_available_items' ) );
58 add_action( 'wp_ajax_search-available-menu-items-customizer', array( $this, 'ajax_search_available_items' ) );
59 add_action( 'customize_controls_enqueue_scripts', array( $this, 'enqueue_scripts' ) );
61 // Needs to run after core Navigation section is set up.
62 add_action( 'customize_register', array( $this, 'customize_register' ), 11 );
64 add_filter( 'customize_dynamic_setting_args', array( $this, 'filter_dynamic_setting_args' ), 10, 2 );
65 add_filter( 'customize_dynamic_setting_class', array( $this, 'filter_dynamic_setting_class' ), 10, 3 );
66 add_action( 'customize_controls_print_footer_scripts', array( $this, 'print_templates' ) );
67 add_action( 'customize_controls_print_footer_scripts', array( $this, 'available_items_template' ) );
68 add_action( 'customize_preview_init', array( $this, 'customize_preview_init' ) );
70 // Selective Refresh partials.
71 add_filter( 'customize_dynamic_partial_args', array( $this, 'customize_dynamic_partial_args' ), 10, 2 );
75 * Adds a nonce for customizing menus.
80 * @param array $nonces Array of nonces.
81 * @return array $nonces Modified array of nonces.
83 public function filter_nonces( $nonces ) {
84 $nonces['customize-menus'] = wp_create_nonce( 'customize-menus' );
89 * Ajax handler for loading available menu items.
94 public function ajax_load_available_items() {
95 check_ajax_referer( 'customize-menus', 'customize-menus-nonce' );
97 if ( ! current_user_can( 'edit_theme_options' ) ) {
101 if ( empty( $_POST['type'] ) || empty( $_POST['object'] ) ) {
102 wp_send_json_error( 'nav_menus_missing_type_or_object_parameter' );
105 $type = sanitize_key( $_POST['type'] );
106 $object = sanitize_key( $_POST['object'] );
107 $page = empty( $_POST['page'] ) ? 0 : absint( $_POST['page'] );
108 $items = $this->load_available_items_query( $type, $object, $page );
110 if ( is_wp_error( $items ) ) {
111 wp_send_json_error( $items->get_error_code() );
113 wp_send_json_success( array( 'items' => $items ) );
118 * Performs the post_type and taxonomy queries for loading available menu items.
123 * @param string $type Optional. Accepts any custom object type and has built-in support for
124 * 'post_type' and 'taxonomy'. Default is 'post_type'.
125 * @param string $object Optional. Accepts any registered taxonomy or post type name. Default is 'page'.
126 * @param int $page Optional. The page number used to generate the query offset. Default is '0'.
127 * @return WP_Error|array Returns either a WP_Error object or an array of menu items.
129 public function load_available_items_query( $type = 'post_type', $object = 'page', $page = 0 ) {
132 if ( 'post_type' === $type ) {
133 $post_type = get_post_type_object( $object );
134 if ( ! $post_type ) {
135 return new WP_Error( 'nav_menus_invalid_post_type' );
138 if ( 0 === $page && 'page' === $object ) {
139 // Add "Home" link. Treat as a page, but switch to custom on add.
142 'title' => _x( 'Home', 'nav menu home label' ),
144 'type_label' => __( 'Custom Link' ),
148 } elseif ( 'post' !== $object && 0 === $page && $post_type->has_archive ) {
149 // Add a post type archive link.
151 'id' => $object . '-archive',
152 'title' => $post_type->labels->archives,
153 'type' => 'post_type_archive',
154 'type_label' => __( 'Post Type Archive' ),
156 'url' => get_post_type_archive_link( $object ),
160 $posts = get_posts( array(
162 'offset' => 10 * $page,
165 'post_type' => $object,
167 foreach ( $posts as $post ) {
168 $post_title = $post->post_title;
169 if ( '' === $post_title ) {
170 /* translators: %d: ID of a post */
171 $post_title = sprintf( __( '#%d (no title)' ), $post->ID );
174 'id' => "post-{$post->ID}",
175 'title' => html_entity_decode( $post_title, ENT_QUOTES, get_bloginfo( 'charset' ) ),
176 'type' => 'post_type',
177 'type_label' => get_post_type_object( $post->post_type )->labels->singular_name,
178 'object' => $post->post_type,
179 'object_id' => intval( $post->ID ),
180 'url' => get_permalink( intval( $post->ID ) ),
183 } elseif ( 'taxonomy' === $type ) {
184 $terms = get_terms( $object, array(
187 'hide_empty' => false,
191 'offset' => 10 * $page,
193 'orderby' => 'count',
194 'pad_counts' => false,
196 if ( is_wp_error( $terms ) ) {
200 foreach ( $terms as $term ) {
202 'id' => "term-{$term->term_id}",
203 'title' => html_entity_decode( $term->name, ENT_QUOTES, get_bloginfo( 'charset' ) ),
204 'type' => 'taxonomy',
205 'type_label' => get_taxonomy( $term->taxonomy )->labels->singular_name,
206 'object' => $term->taxonomy,
207 'object_id' => intval( $term->term_id ),
208 'url' => get_term_link( intval( $term->term_id ), $term->taxonomy ),
214 * Filters the available menu items.
218 * @param array $items The array of menu items.
219 * @param string $type The object type.
220 * @param string $object The object name.
221 * @param int $page The current page number.
223 $items = apply_filters( 'customize_nav_menu_available_items', $items, $type, $object, $page );
229 * Ajax handler for searching available menu items.
234 public function ajax_search_available_items() {
235 check_ajax_referer( 'customize-menus', 'customize-menus-nonce' );
237 if ( ! current_user_can( 'edit_theme_options' ) ) {
241 if ( empty( $_POST['search'] ) ) {
242 wp_send_json_error( 'nav_menus_missing_search_parameter' );
245 $p = isset( $_POST['page'] ) ? absint( $_POST['page'] ) : 0;
250 $s = sanitize_text_field( wp_unslash( $_POST['search'] ) );
251 $items = $this->search_available_items_query( array( 'pagenum' => $p, 's' => $s ) );
253 if ( empty( $items ) ) {
254 wp_send_json_error( array( 'message' => __( 'No results found.' ) ) );
256 wp_send_json_success( array( 'items' => $items ) );
261 * Performs post queries for available-item searching.
263 * Based on WP_Editor::wp_link_query().
268 * @param array $args Optional. Accepts 'pagenum' and 's' (search) arguments.
269 * @return array Menu items.
271 public function search_available_items_query( $args = array() ) {
274 $post_type_objects = get_post_types( array( 'show_in_nav_menus' => true ), 'objects' );
276 'post_type' => array_keys( $post_type_objects ),
277 'suppress_filters' => true,
278 'update_post_term_cache' => false,
279 'update_post_meta_cache' => false,
280 'post_status' => 'publish',
281 'posts_per_page' => 20,
284 $args['pagenum'] = isset( $args['pagenum'] ) ? absint( $args['pagenum'] ) : 1;
285 $query['offset'] = $args['pagenum'] > 1 ? $query['posts_per_page'] * ( $args['pagenum'] - 1 ) : 0;
287 if ( isset( $args['s'] ) ) {
288 $query['s'] = $args['s'];
292 $get_posts = new WP_Query( $query );
294 // Check if any posts were found.
295 if ( $get_posts->post_count ) {
296 foreach ( $get_posts->posts as $post ) {
297 $post_title = $post->post_title;
298 if ( '' === $post_title ) {
299 /* translators: %d: ID of a post */
300 $post_title = sprintf( __( '#%d (no title)' ), $post->ID );
303 'id' => 'post-' . $post->ID,
304 'title' => html_entity_decode( $post_title, ENT_QUOTES, get_bloginfo( 'charset' ) ),
305 'type' => 'post_type',
306 'type_label' => $post_type_objects[ $post->post_type ]->labels->singular_name,
307 'object' => $post->post_type,
308 'object_id' => intval( $post->ID ),
309 'url' => get_permalink( intval( $post->ID ) ),
314 // Query taxonomy terms.
315 $taxonomies = get_taxonomies( array( 'show_in_nav_menus' => true ), 'names' );
316 $terms = get_terms( $taxonomies, array(
317 'name__like' => $args['s'],
319 'offset' => 20 * ($args['pagenum'] - 1),
322 // Check if any taxonomies were found.
323 if ( ! empty( $terms ) ) {
324 foreach ( $terms as $term ) {
326 'id' => 'term-' . $term->term_id,
327 'title' => html_entity_decode( $term->name, ENT_QUOTES, get_bloginfo( 'charset' ) ),
328 'type' => 'taxonomy',
329 'type_label' => get_taxonomy( $term->taxonomy )->labels->singular_name,
330 'object' => $term->taxonomy,
331 'object_id' => intval( $term->term_id ),
332 'url' => get_term_link( intval( $term->term_id ), $term->taxonomy ),
338 * Filters the available menu items during a search request.
342 * @param array $items The array of menu items.
343 * @param array $args Includes 'pagenum' and 's' (search) arguments.
345 $items = apply_filters( 'customize_nav_menu_searched_items', $items, $args );
351 * Enqueue scripts and styles for Customizer pane.
356 public function enqueue_scripts() {
357 wp_enqueue_style( 'customize-nav-menus' );
358 wp_enqueue_script( 'customize-nav-menus' );
360 $temp_nav_menu_setting = new WP_Customize_Nav_Menu_Setting( $this->manager, 'nav_menu[-1]' );
361 $temp_nav_menu_item_setting = new WP_Customize_Nav_Menu_Item_Setting( $this->manager, 'nav_menu_item[-1]' );
365 'allMenus' => wp_get_nav_menus(),
366 'itemTypes' => $this->available_item_types(),
368 'untitled' => _x( '(no label)', 'missing menu item navigation label' ),
369 'unnamed' => _x( '(unnamed)', 'Missing menu name.' ),
370 'custom_label' => __( 'Custom Link' ),
371 /* translators: %s: menu location */
372 'menuLocation' => _x( '(Currently set to: %s)', 'menu' ),
373 'menuNameLabel' => __( 'Menu Name' ),
374 'itemAdded' => __( 'Menu item added' ),
375 'itemDeleted' => __( 'Menu item deleted' ),
376 'menuAdded' => __( 'Menu created' ),
377 'menuDeleted' => __( 'Menu deleted' ),
378 'movedUp' => __( 'Menu item moved up' ),
379 'movedDown' => __( 'Menu item moved down' ),
380 'movedLeft' => __( 'Menu item moved out of submenu' ),
381 'movedRight' => __( 'Menu item is now a sub-item' ),
382 /* translators: ▸ is the unicode right-pointing triangle, and %s is the section title in the Customizer */
383 'customizingMenus' => sprintf( __( 'Customizing ▸ %s' ), esc_html( $this->manager->get_panel( 'nav_menus' )->title ) ),
384 /* translators: %s: title of menu item which is invalid */
385 'invalidTitleTpl' => __( '%s (Invalid)' ),
386 /* translators: %s: title of menu item in draft status */
387 'pendingTitleTpl' => __( '%s (Pending)' ),
388 'itemsFound' => __( 'Number of items found: %d' ),
389 'itemsFoundMore' => __( 'Additional items found: %d' ),
390 'itemsLoadingMore' => __( 'Loading more results... please wait.' ),
391 'reorderModeOn' => __( 'Reorder mode enabled' ),
392 'reorderModeOff' => __( 'Reorder mode closed' ),
393 'reorderLabelOn' => esc_attr__( 'Reorder menu items' ),
394 'reorderLabelOff' => esc_attr__( 'Close reorder mode' ),
396 'settingTransport' => 'postMessage',
397 'phpIntMax' => PHP_INT_MAX,
398 'defaultSettingValues' => array(
399 'nav_menu' => $temp_nav_menu_setting->default,
400 'nav_menu_item' => $temp_nav_menu_item_setting->default,
402 'locationSlugMappedToName' => get_registered_nav_menus(),
405 $data = sprintf( 'var _wpCustomizeNavMenusSettings = %s;', wp_json_encode( $settings ) );
406 wp_scripts()->add_data( 'customize-nav-menus', 'data', $data );
408 // This is copied from nav-menus.php, and it has an unfortunate object name of `menus`.
409 $nav_menus_l10n = array(
410 'oneThemeLocationNoMenus' => null,
411 'moveUp' => __( 'Move up one' ),
412 'moveDown' => __( 'Move down one' ),
413 'moveToTop' => __( 'Move to the top' ),
414 /* translators: %s: previous item name */
415 'moveUnder' => __( 'Move under %s' ),
416 /* translators: %s: previous item name */
417 'moveOutFrom' => __( 'Move out from under %s' ),
418 /* translators: %s: previous item name */
419 'under' => __( 'Under %s' ),
420 /* translators: %s: previous item name */
421 'outFrom' => __( 'Out from under %s' ),
422 /* translators: 1: item name, 2: item position, 3: total number of items */
423 'menuFocus' => __( '%1$s. Menu item %2$d of %3$d.' ),
424 /* translators: 1: item name, 2: item position, 3: parent item name */
425 'subMenuFocus' => __( '%1$s. Sub item number %2$d under %3$s.' ),
427 wp_localize_script( 'nav-menu', 'menus', $nav_menus_l10n );
431 * Filters a dynamic setting's constructor args.
433 * For a dynamic setting to be registered, this filter must be employed
434 * to override the default false value with an array of args to pass to
435 * the WP_Customize_Setting constructor.
440 * @param false|array $setting_args The arguments to the WP_Customize_Setting constructor.
441 * @param string $setting_id ID for dynamic setting, usually coming from `$_POST['customized']`.
442 * @return array|false
444 public function filter_dynamic_setting_args( $setting_args, $setting_id ) {
445 if ( preg_match( WP_Customize_Nav_Menu_Setting::ID_PATTERN, $setting_id ) ) {
446 $setting_args = array(
447 'type' => WP_Customize_Nav_Menu_Setting::TYPE,
448 'transport' => 'postMessage',
450 } elseif ( preg_match( WP_Customize_Nav_Menu_Item_Setting::ID_PATTERN, $setting_id ) ) {
451 $setting_args = array(
452 'type' => WP_Customize_Nav_Menu_Item_Setting::TYPE,
453 'transport' => 'postMessage',
456 return $setting_args;
460 * Allow non-statically created settings to be constructed with custom WP_Customize_Setting subclass.
465 * @param string $setting_class WP_Customize_Setting or a subclass.
466 * @param string $setting_id ID for dynamic setting, usually coming from `$_POST['customized']`.
467 * @param array $setting_args WP_Customize_Setting or a subclass.
470 public function filter_dynamic_setting_class( $setting_class, $setting_id, $setting_args ) {
471 unset( $setting_id );
473 if ( ! empty( $setting_args['type'] ) && WP_Customize_Nav_Menu_Setting::TYPE === $setting_args['type'] ) {
474 $setting_class = 'WP_Customize_Nav_Menu_Setting';
475 } elseif ( ! empty( $setting_args['type'] ) && WP_Customize_Nav_Menu_Item_Setting::TYPE === $setting_args['type'] ) {
476 $setting_class = 'WP_Customize_Nav_Menu_Item_Setting';
478 return $setting_class;
482 * Add the customizer settings and controls.
487 public function customize_register() {
489 // Require JS-rendered control types.
490 $this->manager->register_panel_type( 'WP_Customize_Nav_Menus_Panel' );
491 $this->manager->register_control_type( 'WP_Customize_Nav_Menu_Control' );
492 $this->manager->register_control_type( 'WP_Customize_Nav_Menu_Name_Control' );
493 $this->manager->register_control_type( 'WP_Customize_Nav_Menu_Auto_Add_Control' );
494 $this->manager->register_control_type( 'WP_Customize_Nav_Menu_Item_Control' );
496 // Create a panel for Menus.
497 $description = '<p>' . __( 'This panel is used for managing navigation menus for content you have already published on your site. You can create menus and add items for existing content such as pages, posts, categories, tags, formats, or custom links.' ) . '</p>';
498 if ( current_theme_supports( 'widgets' ) ) {
499 /* translators: URL to the widgets panel of the customizer */
500 $description .= '<p>' . sprintf( __( 'Menus can be displayed in locations defined by your theme or in <a href="%s">widget areas</a> by adding a “Custom Menu” widget.' ), "javascript:wp.customize.panel( 'widgets' ).focus();" ) . '</p>';
502 $description .= '<p>' . __( 'Menus can be displayed in locations defined by your theme.' ) . '</p>';
504 $this->manager->add_panel( new WP_Customize_Nav_Menus_Panel( $this->manager, 'nav_menus', array(
505 'title' => __( 'Menus' ),
506 'description' => $description,
508 // 'theme_supports' => 'menus|widgets', @todo allow multiple theme supports
510 $menus = wp_get_nav_menus();
513 $locations = get_registered_nav_menus();
514 $num_locations = count( array_keys( $locations ) );
515 if ( 1 == $num_locations ) {
516 $description = '<p>' . __( 'Your theme supports one menu. Select which menu you would like to use.' ) . '</p>';
518 /* translators: %s: number of menu locations */
519 $description = '<p>' . sprintf( _n( 'Your theme supports %s menu. Select which menu appears in each location.', 'Your theme supports %s menus. Select which menu appears in each location.', $num_locations ), number_format_i18n( $num_locations ) ) . '</p>';
521 if ( current_theme_supports( 'widgets' ) ) {
522 /* translators: URL to the widgets panel of the customizer */
523 $description .= '<p>' . sprintf( __( 'You can also place menus in <a href="%s">widget areas</a> with the “Custom Menu” widget.' ), "javascript:wp.customize.panel( 'widgets' ).focus();" ) . '</p>';
526 $this->manager->add_section( 'menu_locations', array(
527 'title' => __( 'Menu Locations' ),
528 'panel' => 'nav_menus',
530 'description' => $description,
533 $choices = array( '0' => __( '— Select —' ) );
534 foreach ( $menus as $menu ) {
535 $choices[ $menu->term_id ] = wp_html_excerpt( $menu->name, 40, '…' );
538 foreach ( $locations as $location => $description ) {
539 $setting_id = "nav_menu_locations[{$location}]";
541 $setting = $this->manager->get_setting( $setting_id );
543 $setting->transport = 'postMessage';
544 remove_filter( "customize_sanitize_{$setting_id}", 'absint' );
545 add_filter( "customize_sanitize_{$setting_id}", array( $this, 'intval_base10' ) );
547 $this->manager->add_setting( $setting_id, array(
548 'sanitize_callback' => array( $this, 'intval_base10' ),
549 'theme_supports' => 'menus',
550 'type' => 'theme_mod',
551 'transport' => 'postMessage',
556 $this->manager->add_control( new WP_Customize_Nav_Menu_Location_Control( $this->manager, $setting_id, array(
557 'label' => $description,
558 'location_id' => $location,
559 'section' => 'menu_locations',
560 'choices' => $choices,
564 // Register each menu as a Customizer section, and add each menu item to each menu.
565 foreach ( $menus as $menu ) {
566 $menu_id = $menu->term_id;
568 // Create a section for each menu.
569 $section_id = 'nav_menu[' . $menu_id . ']';
570 $this->manager->add_section( new WP_Customize_Nav_Menu_Section( $this->manager, $section_id, array(
571 'title' => html_entity_decode( $menu->name, ENT_QUOTES, get_bloginfo( 'charset' ) ),
573 'panel' => 'nav_menus',
576 $nav_menu_setting_id = 'nav_menu[' . $menu_id . ']';
577 $this->manager->add_setting( new WP_Customize_Nav_Menu_Setting( $this->manager, $nav_menu_setting_id, array(
578 'transport' => 'postMessage',
581 // Add the menu contents.
582 $menu_items = (array) wp_get_nav_menu_items( $menu_id );
584 foreach ( array_values( $menu_items ) as $i => $item ) {
586 // Create a setting for each menu item (which doesn't actually manage data, currently).
587 $menu_item_setting_id = 'nav_menu_item[' . $item->ID . ']';
589 $value = (array) $item;
590 $value['nav_menu_term_id'] = $menu_id;
591 $this->manager->add_setting( new WP_Customize_Nav_Menu_Item_Setting( $this->manager, $menu_item_setting_id, array(
593 'transport' => 'postMessage',
596 // Create a control for each menu item.
597 $this->manager->add_control( new WP_Customize_Nav_Menu_Item_Control( $this->manager, $menu_item_setting_id, array(
598 'label' => $item->title,
599 'section' => $section_id,
600 'priority' => 10 + $i,
604 // Note: other controls inside of this section get added dynamically in JS via the MenuSection.ready() function.
607 // Add the add-new-menu section and controls.
608 $this->manager->add_section( new WP_Customize_New_Menu_Section( $this->manager, 'add_menu', array(
609 'title' => __( 'Add a Menu' ),
610 'panel' => 'nav_menus',
614 $this->manager->add_control( 'new_menu_name', array(
616 'section' => 'add_menu',
618 'settings' => array(),
619 'input_attrs' => array(
620 'class' => 'menu-name-field',
621 'placeholder' => __( 'New menu name' ),
625 $this->manager->add_control( new WP_Customize_New_Menu_Control( $this->manager, 'create_new_menu', array(
626 'section' => 'add_menu',
627 'settings' => array(),
632 * Get the base10 intval.
634 * This is used as a setting's sanitize_callback; we can't use just plain
635 * intval because the second argument is not what intval() expects.
640 * @param mixed $value Number to convert.
641 * @return int Integer.
643 public function intval_base10( $value ) {
644 return intval( $value, 10 );
648 * Return an array of all the available item types.
653 * @return array The available menu item types.
655 public function available_item_types() {
656 $item_types = array();
658 $post_types = get_post_types( array( 'show_in_nav_menus' => true ), 'objects' );
660 foreach ( $post_types as $slug => $post_type ) {
661 $item_types[] = array(
662 'title' => $post_type->labels->name,
663 'type' => 'post_type',
664 'object' => $post_type->name,
669 $taxonomies = get_taxonomies( array( 'show_in_nav_menus' => true ), 'objects' );
671 foreach ( $taxonomies as $slug => $taxonomy ) {
672 if ( 'post_format' === $taxonomy && ! current_theme_supports( 'post-formats' ) ) {
675 $item_types[] = array(
676 'title' => $taxonomy->labels->name,
677 'type' => 'taxonomy',
678 'object' => $taxonomy->name,
684 * Filters the available menu item types.
688 * @param array $item_types Custom menu item types.
690 $item_types = apply_filters( 'customize_nav_menu_available_item_types', $item_types );
696 * Print the JavaScript templates used to render Menu Customizer components.
698 * Templates are imported into the JS use wp.template.
703 public function print_templates() {
705 <script type="text/html" id="tmpl-available-menu-item">
706 <li id="menu-item-tpl-{{ data.id }}" class="menu-item-tpl" data-menu-item-id="{{ data.id }}">
707 <div class="menu-item-bar">
708 <div class="menu-item-handle">
709 <span class="item-type" aria-hidden="true">{{ data.type_label }}</span>
710 <span class="item-title" aria-hidden="true">
711 <span class="menu-item-title<# if ( ! data.title ) { #> no-title<# } #>">{{ data.title || wp.customize.Menus.data.l10n.untitled }}</span>
713 <button type="button" class="button-link item-add">
714 <span class="screen-reader-text"><?php
715 /* translators: 1: Title of a menu item, 2: Type of a menu item */
716 printf( __( 'Add to menu: %1$s (%2$s)' ), '{{ data.title || wp.customize.Menus.data.l10n.untitled }}', '{{ data.type_label }}' );
724 <script type="text/html" id="tmpl-menu-item-reorder-nav">
725 <div class="menu-item-reorder-nav">
728 '<button type="button" class="menus-move-up">%1$s</button><button type="button" class="menus-move-down">%2$s</button><button type="button" class="menus-move-left">%3$s</button><button type="button" class="menus-move-right">%4$s</button>',
731 __( 'Move one level up' ),
732 __( 'Move one level down' )
741 * Print the html template used to render the add-menu-item frame.
746 public function available_items_template() {
748 <div id="available-menu-items" class="accordion-container">
749 <div class="customize-section-title">
750 <button type="button" class="customize-section-back" tabindex="-1">
751 <span class="screen-reader-text"><?php _e( 'Back' ); ?></span>
754 <span class="customize-action">
756 /* translators: ▸ is the unicode right-pointing triangle, and %s is the section title in the Customizer */
757 printf( __( 'Customizing ▸ %s' ), esc_html( $this->manager->get_panel( 'nav_menus' )->title ) );
760 <?php _e( 'Add Menu Items' ); ?>
763 <div id="available-menu-items-search" class="accordion-section cannot-expand">
764 <div class="accordion-section-title">
765 <label class="screen-reader-text" for="menu-items-search"><?php _e( 'Search Menu Items' ); ?></label>
766 <input type="text" id="menu-items-search" placeholder="<?php esc_attr_e( 'Search menu items…' ) ?>" aria-describedby="menu-items-search-desc" />
767 <p class="screen-reader-text" id="menu-items-search-desc"><?php _e( 'The search results will be updated as you type.' ); ?></p>
768 <span class="spinner"></span>
770 <button type="button" class="clear-results"><span class="screen-reader-text"><?php _e( 'Clear Results' ); ?></span></button>
771 <ul class="accordion-section-content" data-type="search"></ul>
773 <div id="new-custom-menu-item" class="accordion-section">
774 <h4 class="accordion-section-title" role="presentation">
775 <?php _e( 'Custom Links' ); ?>
776 <button type="button" class="button-link" aria-expanded="false">
777 <span class="screen-reader-text"><?php _e( 'Toggle section: Custom Links' ); ?></span>
778 <span class="toggle-indicator" aria-hidden="true"></span>
781 <div class="accordion-section-content customlinkdiv">
782 <input type="hidden" value="custom" id="custom-menu-item-type" name="menu-item[-1][menu-item-type]" />
783 <p id="menu-item-url-wrap" class="wp-clearfix">
784 <label class="howto" for="custom-menu-item-url"><?php _e( 'URL' ); ?></label>
785 <input id="custom-menu-item-url" name="menu-item[-1][menu-item-url]" type="text" class="code menu-item-textbox" value="http://">
787 <p id="menu-item-name-wrap" class="wp-clearfix">
788 <label class="howto" for="custom-menu-item-name"><?php _e( 'Link Text' ); ?></label>
789 <input id="custom-menu-item-name" name="menu-item[-1][menu-item-title]" type="text" class="regular-text menu-item-textbox">
791 <p class="button-controls">
792 <span class="add-to-menu">
793 <input type="submit" class="button-secondary submit-add-to-menu right" value="<?php esc_attr_e( 'Add to Menu' ); ?>" name="add-custom-menu-item" id="custom-menu-item-submit">
794 <span class="spinner"></span>
800 // Containers for per-post-type item browsing; items added with JS.
801 foreach ( $this->available_item_types() as $available_item_type ) {
802 $id = sprintf( 'available-menu-items-%s-%s', $available_item_type['type'], $available_item_type['object'] );
804 <div id="<?php echo esc_attr( $id ); ?>" class="accordion-section">
805 <h4 class="accordion-section-title" role="presentation">
806 <?php echo esc_html( $available_item_type['title'] ); ?>
807 <span class="spinner"></span>
808 <span class="no-items"><?php _e( 'No items' ); ?></span>
809 <button type="button" class="button-link" aria-expanded="false">
810 <span class="screen-reader-text"><?php
811 /* translators: %s: Title of a section with menu items */
812 printf( __( 'Toggle section: %s' ), esc_html( $available_item_type['title'] ) ); ?></span>
813 <span class="toggle-indicator" aria-hidden="true"></span>
816 <ul class="accordion-section-content" data-type="<?php echo esc_attr( $available_item_type['type'] ); ?>" data-object="<?php echo esc_attr( $available_item_type['object'] ); ?>"></ul>
821 </div><!-- #available-menu-items -->
826 // Start functionality specific to partial-refresh of menu changes in Customizer preview.
830 * Nav menu args used for each instance, keyed by the args HMAC.
836 public $preview_nav_menu_instance_args = array();
839 * Filters arguments for dynamic nav_menu selective refresh partials.
844 * @param array|false $partial_args Partial args.
845 * @param string $partial_id Partial ID.
846 * @return array Partial args.
848 public function customize_dynamic_partial_args( $partial_args, $partial_id ) {
850 if ( preg_match( '/^nav_menu_instance\[[0-9a-f]{32}\]$/', $partial_id ) ) {
851 if ( false === $partial_args ) {
852 $partial_args = array();
854 $partial_args = array_merge(
857 'type' => 'nav_menu_instance',
858 'render_callback' => array( $this, 'render_nav_menu_partial' ),
859 'container_inclusive' => true,
860 'settings' => array(), // Empty because the nav menu instance may relate to a menu or a location.
861 'capability' => 'edit_theme_options',
866 return $partial_args;
870 * Add hooks for the Customizer preview.
875 public function customize_preview_init() {
876 add_action( 'wp_enqueue_scripts', array( $this, 'customize_preview_enqueue_deps' ) );
877 add_filter( 'wp_nav_menu_args', array( $this, 'filter_wp_nav_menu_args' ), 1000 );
878 add_filter( 'wp_nav_menu', array( $this, 'filter_wp_nav_menu' ), 10, 2 );
879 add_filter( 'wp_footer', array( $this, 'export_preview_data' ), 1 );
880 add_filter( 'customize_render_partials_response', array( $this, 'export_partial_rendered_nav_menu_instances' ) );
884 * Keep track of the arguments that are being passed to wp_nav_menu().
889 * @see WP_Customize_Widgets_Partial_Refresh::filter_dynamic_sidebar_params()
891 * @param array $args An array containing wp_nav_menu() arguments.
892 * @return array Arguments.
894 public function filter_wp_nav_menu_args( $args ) {
896 * The following conditions determine whether or not this instance of
897 * wp_nav_menu() can use selective refreshed. A wp_nav_menu() can be
898 * selective refreshed if...
900 $can_partial_refresh = (
901 // ...if wp_nav_menu() is directly echoing out the menu (and thus isn't manipulating the string after generated),
902 ! empty( $args['echo'] )
904 // ...and if the fallback_cb can be serialized to JSON, since it will be included in the placement context data,
905 ( empty( $args['fallback_cb'] ) || is_string( $args['fallback_cb'] ) )
907 // ...and if the walker can also be serialized to JSON, since it will be included in the placement context data as well,
908 ( empty( $args['walker'] ) || is_string( $args['walker'] ) )
909 // ...and if it has a theme location assigned or an assigned menu to display,
911 ! empty( $args['theme_location'] )
913 ( ! empty( $args['menu'] ) && ( is_numeric( $args['menu'] ) || is_object( $args['menu'] ) ) )
916 // ...and if the nav menu would be rendered with a wrapper container element (upon which to attach data-* attributes).
918 ! empty( $args['container'] )
920 ( isset( $args['items_wrap'] ) && '<' === substr( $args['items_wrap'], 0, 1 ) )
923 $args['can_partial_refresh'] = $can_partial_refresh;
925 $exported_args = $args;
927 // Empty out args which may not be JSON-serializable.
928 if ( ! $can_partial_refresh ) {
929 $exported_args['fallback_cb'] = '';
930 $exported_args['walker'] = '';
934 * Replace object menu arg with a term_id menu arg, as this exports better
935 * to JS and is easier to compare hashes.
937 if ( ! empty( $exported_args['menu'] ) && is_object( $exported_args['menu'] ) ) {
938 $exported_args['menu'] = $exported_args['menu']->term_id;
941 ksort( $exported_args );
942 $exported_args['args_hmac'] = $this->hash_nav_menu_args( $exported_args );
944 $args['customize_preview_nav_menus_args'] = $exported_args;
945 $this->preview_nav_menu_instance_args[ $exported_args['args_hmac'] ] = $exported_args;
950 * Prepares wp_nav_menu() calls for partial refresh.
952 * Injects attributes into container element.
959 * @param string $nav_menu_content The HTML content for the navigation menu.
960 * @param object $args An object containing wp_nav_menu() arguments.
963 public function filter_wp_nav_menu( $nav_menu_content, $args ) {
964 if ( isset( $args->customize_preview_nav_menus_args['can_partial_refresh'] ) && $args->customize_preview_nav_menus_args['can_partial_refresh'] ) {
965 $attributes = sprintf( ' data-customize-partial-id="%s"', esc_attr( 'nav_menu_instance[' . $args->customize_preview_nav_menus_args['args_hmac'] . ']' ) );
966 $attributes .= ' data-customize-partial-type="nav_menu_instance"';
967 $attributes .= sprintf( ' data-customize-partial-placement-context="%s"', esc_attr( wp_json_encode( $args->customize_preview_nav_menus_args ) ) );
968 $nav_menu_content = preg_replace( '#^(<\w+)#', '$1 ' . $attributes, $nav_menu_content, 1 );
970 return $nav_menu_content;
974 * Hashes (hmac) the nav menu arguments to ensure they are not tampered with when
975 * submitted in the Ajax request.
977 * Note that the array is expected to be pre-sorted.
982 * @param array $args The arguments to hash.
983 * @return string Hashed nav menu arguments.
985 public function hash_nav_menu_args( $args ) {
986 return wp_hash( serialize( $args ) );
990 * Enqueue scripts for the Customizer preview.
995 public function customize_preview_enqueue_deps() {
996 wp_enqueue_script( 'customize-preview-nav-menus' ); // Note that we have overridden this.
997 wp_enqueue_style( 'customize-preview' );
1001 * Exports data from PHP to JS.
1006 public function export_preview_data() {
1008 // Why not wp_localize_script? Because we're not localizing, and it forces values into strings.
1010 'navMenuInstanceArgs' => $this->preview_nav_menu_instance_args,
1012 printf( '<script>var _wpCustomizePreviewNavMenusExports = %s;</script>', wp_json_encode( $exports ) );
1016 * Export any wp_nav_menu() calls during the rendering of any partials.
1021 * @param array $response Response.
1022 * @return array Response.
1024 public function export_partial_rendered_nav_menu_instances( $response ) {
1025 $response['nav_menu_instance_args'] = $this->preview_nav_menu_instance_args;
1030 * Render a specific menu via wp_nav_menu() using the supplied arguments.
1035 * @see wp_nav_menu()
1037 * @param WP_Customize_Partial $partial Partial.
1038 * @param array $nav_menu_args Nav menu args supplied as container context.
1039 * @return string|false
1041 public function render_nav_menu_partial( $partial, $nav_menu_args ) {
1044 if ( ! isset( $nav_menu_args['args_hmac'] ) ) {
1045 // Error: missing_args_hmac.
1049 $nav_menu_args_hmac = $nav_menu_args['args_hmac'];
1050 unset( $nav_menu_args['args_hmac'] );
1052 ksort( $nav_menu_args );
1053 if ( ! hash_equals( $this->hash_nav_menu_args( $nav_menu_args ), $nav_menu_args_hmac ) ) {
1054 // Error: args_hmac_mismatch.
1059 wp_nav_menu( $nav_menu_args );
1060 $content = ob_get_clean();