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 * Filter 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 * Filter 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 * Filter 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 $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>';
501 $description .= '<p>' . __( 'Menus can be displayed in locations defined by your theme.' ) . '</p>';
503 $this->manager->add_panel( new WP_Customize_Nav_Menus_Panel( $this->manager, 'nav_menus', array(
504 'title' => __( 'Menus' ),
505 'description' => $description,
507 // 'theme_supports' => 'menus|widgets', @todo allow multiple theme supports
509 $menus = wp_get_nav_menus();
512 $locations = get_registered_nav_menus();
513 $num_locations = count( array_keys( $locations ) );
514 if ( 1 == $num_locations ) {
515 $description = '<p>' . __( 'Your theme supports one menu. Select which menu you would like to use.' );
517 $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 ) );
519 $description .= '</p><p>' . __( 'You can also place menus in widget areas with the Custom Menu widget.' ) . '</p>';
521 $this->manager->add_section( 'menu_locations', array(
522 'title' => __( 'Menu Locations' ),
523 'panel' => 'nav_menus',
525 'description' => $description,
528 $choices = array( '0' => __( '— Select —' ) );
529 foreach ( $menus as $menu ) {
530 $choices[ $menu->term_id ] = wp_html_excerpt( $menu->name, 40, '…' );
533 foreach ( $locations as $location => $description ) {
534 $setting_id = "nav_menu_locations[{$location}]";
536 $setting = $this->manager->get_setting( $setting_id );
538 $setting->transport = 'postMessage';
539 remove_filter( "customize_sanitize_{$setting_id}", 'absint' );
540 add_filter( "customize_sanitize_{$setting_id}", array( $this, 'intval_base10' ) );
542 $this->manager->add_setting( $setting_id, array(
543 'sanitize_callback' => array( $this, 'intval_base10' ),
544 'theme_supports' => 'menus',
545 'type' => 'theme_mod',
546 'transport' => 'postMessage',
551 $this->manager->add_control( new WP_Customize_Nav_Menu_Location_Control( $this->manager, $setting_id, array(
552 'label' => $description,
553 'location_id' => $location,
554 'section' => 'menu_locations',
555 'choices' => $choices,
559 // Register each menu as a Customizer section, and add each menu item to each menu.
560 foreach ( $menus as $menu ) {
561 $menu_id = $menu->term_id;
563 // Create a section for each menu.
564 $section_id = 'nav_menu[' . $menu_id . ']';
565 $this->manager->add_section( new WP_Customize_Nav_Menu_Section( $this->manager, $section_id, array(
566 'title' => html_entity_decode( $menu->name, ENT_QUOTES, get_bloginfo( 'charset' ) ),
568 'panel' => 'nav_menus',
571 $nav_menu_setting_id = 'nav_menu[' . $menu_id . ']';
572 $this->manager->add_setting( new WP_Customize_Nav_Menu_Setting( $this->manager, $nav_menu_setting_id, array(
573 'transport' => 'postMessage',
576 // Add the menu contents.
577 $menu_items = (array) wp_get_nav_menu_items( $menu_id );
579 foreach ( array_values( $menu_items ) as $i => $item ) {
581 // Create a setting for each menu item (which doesn't actually manage data, currently).
582 $menu_item_setting_id = 'nav_menu_item[' . $item->ID . ']';
584 $value = (array) $item;
585 $value['nav_menu_term_id'] = $menu_id;
586 $this->manager->add_setting( new WP_Customize_Nav_Menu_Item_Setting( $this->manager, $menu_item_setting_id, array(
588 'transport' => 'postMessage',
591 // Create a control for each menu item.
592 $this->manager->add_control( new WP_Customize_Nav_Menu_Item_Control( $this->manager, $menu_item_setting_id, array(
593 'label' => $item->title,
594 'section' => $section_id,
595 'priority' => 10 + $i,
599 // Note: other controls inside of this section get added dynamically in JS via the MenuSection.ready() function.
602 // Add the add-new-menu section and controls.
603 $this->manager->add_section( new WP_Customize_New_Menu_Section( $this->manager, 'add_menu', array(
604 'title' => __( 'Add a Menu' ),
605 'panel' => 'nav_menus',
609 $this->manager->add_control( 'new_menu_name', array(
611 'section' => 'add_menu',
613 'settings' => array(),
614 'input_attrs' => array(
615 'class' => 'menu-name-field',
616 'placeholder' => __( 'New menu name' ),
620 $this->manager->add_control( new WP_Customize_New_Menu_Control( $this->manager, 'create_new_menu', array(
621 'section' => 'add_menu',
622 'settings' => array(),
627 * Get the base10 intval.
629 * This is used as a setting's sanitize_callback; we can't use just plain
630 * intval because the second argument is not what intval() expects.
635 * @param mixed $value Number to convert.
636 * @return int Integer.
638 public function intval_base10( $value ) {
639 return intval( $value, 10 );
643 * Return an array of all the available item types.
648 * @return array The available menu item types.
650 public function available_item_types() {
651 $item_types = array();
653 $post_types = get_post_types( array( 'show_in_nav_menus' => true ), 'objects' );
655 foreach ( $post_types as $slug => $post_type ) {
656 $item_types[] = array(
657 'title' => $post_type->labels->name,
658 'type' => 'post_type',
659 'object' => $post_type->name,
664 $taxonomies = get_taxonomies( array( 'show_in_nav_menus' => true ), 'objects' );
666 foreach ( $taxonomies as $slug => $taxonomy ) {
667 if ( 'post_format' === $taxonomy && ! current_theme_supports( 'post-formats' ) ) {
670 $item_types[] = array(
671 'title' => $taxonomy->labels->name,
672 'type' => 'taxonomy',
673 'object' => $taxonomy->name,
679 * Filter the available menu item types.
683 * @param array $item_types Custom menu item types.
685 $item_types = apply_filters( 'customize_nav_menu_available_item_types', $item_types );
691 * Print the JavaScript templates used to render Menu Customizer components.
693 * Templates are imported into the JS use wp.template.
698 public function print_templates() {
700 <script type="text/html" id="tmpl-available-menu-item">
701 <li id="menu-item-tpl-{{ data.id }}" class="menu-item-tpl" data-menu-item-id="{{ data.id }}">
702 <div class="menu-item-bar">
703 <div class="menu-item-handle">
704 <span class="item-type" aria-hidden="true">{{ data.type_label }}</span>
705 <span class="item-title" aria-hidden="true">
706 <span class="menu-item-title<# if ( ! data.title ) { #> no-title<# } #>">{{ data.title || wp.customize.Menus.data.l10n.untitled }}</span>
708 <button type="button" class="button-link item-add">
709 <span class="screen-reader-text"><?php
710 /* translators: 1: Title of a menu item, 2: Type of a menu item */
711 printf( __( 'Add to menu: %1$s (%2$s)' ), '{{ data.title || wp.customize.Menus.data.l10n.untitled }}', '{{ data.type_label }}' );
719 <script type="text/html" id="tmpl-menu-item-reorder-nav">
720 <div class="menu-item-reorder-nav">
723 '<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>',
726 __( 'Move one level up' ),
727 __( 'Move one level down' )
736 * Print the html template used to render the add-menu-item frame.
741 public function available_items_template() {
743 <div id="available-menu-items" class="accordion-container">
744 <div class="customize-section-title">
745 <button type="button" class="customize-section-back" tabindex="-1">
746 <span class="screen-reader-text"><?php _e( 'Back' ); ?></span>
749 <span class="customize-action">
751 /* translators: ▸ is the unicode right-pointing triangle, and %s is the section title in the Customizer */
752 printf( __( 'Customizing ▸ %s' ), esc_html( $this->manager->get_panel( 'nav_menus' )->title ) );
755 <?php _e( 'Add Menu Items' ); ?>
758 <div id="available-menu-items-search" class="accordion-section cannot-expand">
759 <div class="accordion-section-title">
760 <label class="screen-reader-text" for="menu-items-search"><?php _e( 'Search Menu Items' ); ?></label>
761 <input type="text" id="menu-items-search" placeholder="<?php esc_attr_e( 'Search menu items…' ) ?>" aria-describedby="menu-items-search-desc" />
762 <p class="screen-reader-text" id="menu-items-search-desc"><?php _e( 'The search results will be updated as you type.' ); ?></p>
763 <span class="spinner"></span>
764 <span class="clear-results"><span class="screen-reader-text"><?php _e( 'Clear Results' ); ?></span></span>
766 <ul class="accordion-section-content" data-type="search"></ul>
768 <div id="new-custom-menu-item" class="accordion-section">
769 <h4 class="accordion-section-title" role="presentation">
770 <?php _e( 'Custom Links' ); ?>
771 <button type="button" class="button-link" aria-expanded="false">
772 <span class="screen-reader-text"><?php _e( 'Toggle section: Custom Links' ); ?></span>
773 <span class="toggle-indicator" aria-hidden="true"></span>
776 <div class="accordion-section-content customlinkdiv">
777 <input type="hidden" value="custom" id="custom-menu-item-type" name="menu-item[-1][menu-item-type]" />
778 <p id="menu-item-url-wrap" class="wp-clearfix">
779 <label class="howto" for="custom-menu-item-url"><?php _e( 'URL' ); ?></label>
780 <input id="custom-menu-item-url" name="menu-item[-1][menu-item-url]" type="text" class="code menu-item-textbox" value="http://">
782 <p id="menu-item-name-wrap" class="wp-clearfix">
783 <label class="howto" for="custom-menu-item-name"><?php _e( 'Link Text' ); ?></label>
784 <input id="custom-menu-item-name" name="menu-item[-1][menu-item-title]" type="text" class="regular-text menu-item-textbox">
786 <p class="button-controls">
787 <span class="add-to-menu">
788 <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">
789 <span class="spinner"></span>
795 // Containers for per-post-type item browsing; items added with JS.
796 foreach ( $this->available_item_types() as $available_item_type ) {
797 $id = sprintf( 'available-menu-items-%s-%s', $available_item_type['type'], $available_item_type['object'] );
799 <div id="<?php echo esc_attr( $id ); ?>" class="accordion-section">
800 <h4 class="accordion-section-title" role="presentation">
801 <?php echo esc_html( $available_item_type['title'] ); ?>
802 <span class="spinner"></span>
803 <span class="no-items"><?php _e( 'No items' ); ?></span>
804 <button type="button" class="button-link" aria-expanded="false">
805 <span class="screen-reader-text"><?php
806 /* translators: %s: Title of a section with menu items */
807 printf( __( 'Toggle section: %s' ), esc_html( $available_item_type['title'] ) ); ?></span>
808 <span class="toggle-indicator" aria-hidden="true"></span>
811 <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>
816 </div><!-- #available-menu-items -->
821 // Start functionality specific to partial-refresh of menu changes in Customizer preview.
825 * Nav menu args used for each instance, keyed by the args HMAC.
831 public $preview_nav_menu_instance_args = array();
834 * Filter arguments for dynamic nav_menu selective refresh partials.
839 * @param array|false $partial_args Partial args.
840 * @param string $partial_id Partial ID.
841 * @return array Partial args.
843 public function customize_dynamic_partial_args( $partial_args, $partial_id ) {
845 if ( preg_match( '/^nav_menu_instance\[[0-9a-f]{32}\]$/', $partial_id ) ) {
846 if ( false === $partial_args ) {
847 $partial_args = array();
849 $partial_args = array_merge(
852 'type' => 'nav_menu_instance',
853 'render_callback' => array( $this, 'render_nav_menu_partial' ),
854 'container_inclusive' => true,
855 'settings' => array(), // Empty because the nav menu instance may relate to a menu or a location.
856 'capability' => 'edit_theme_options',
861 return $partial_args;
865 * Add hooks for the Customizer preview.
870 public function customize_preview_init() {
871 add_action( 'wp_enqueue_scripts', array( $this, 'customize_preview_enqueue_deps' ) );
872 add_filter( 'wp_nav_menu_args', array( $this, 'filter_wp_nav_menu_args' ), 1000 );
873 add_filter( 'wp_nav_menu', array( $this, 'filter_wp_nav_menu' ), 10, 2 );
874 add_filter( 'wp_footer', array( $this, 'export_preview_data' ), 1 );
875 add_filter( 'customize_render_partials_response', array( $this, 'export_partial_rendered_nav_menu_instances' ) );
879 * Keep track of the arguments that are being passed to wp_nav_menu().
884 * @see WP_Customize_Widgets_Partial_Refresh::filter_dynamic_sidebar_params()
886 * @param array $args An array containing wp_nav_menu() arguments.
887 * @return array Arguments.
889 public function filter_wp_nav_menu_args( $args ) {
891 * The following conditions determine whether or not this instance of
892 * wp_nav_menu() can use selective refreshed. A wp_nav_menu() can be
893 * selective refreshed if...
895 $can_partial_refresh = (
896 // ...if wp_nav_menu() is directly echoing out the menu (and thus isn't manipulating the string after generated),
897 ! empty( $args['echo'] )
899 // ...and if the fallback_cb can be serialized to JSON, since it will be included in the placement context data,
900 ( empty( $args['fallback_cb'] ) || is_string( $args['fallback_cb'] ) )
902 // ...and if the walker can also be serialized to JSON, since it will be included in the placement context data as well,
903 ( empty( $args['walker'] ) || is_string( $args['walker'] ) )
904 // ...and if it has a theme location assigned or an assigned menu to display,
906 ! empty( $args['theme_location'] )
908 ( ! empty( $args['menu'] ) && ( is_numeric( $args['menu'] ) || is_object( $args['menu'] ) ) )
911 // ...and if the nav menu would be rendered with a wrapper container element (upon which to attach data-* attributes).
913 ! empty( $args['container'] )
915 ( isset( $args['items_wrap'] ) && '<' === substr( $args['items_wrap'], 0, 1 ) )
918 $args['can_partial_refresh'] = $can_partial_refresh;
920 $exported_args = $args;
922 // Empty out args which may not be JSON-serializable.
923 if ( ! $can_partial_refresh ) {
924 $exported_args['fallback_cb'] = '';
925 $exported_args['walker'] = '';
929 * Replace object menu arg with a term_id menu arg, as this exports better
930 * to JS and is easier to compare hashes.
932 if ( ! empty( $exported_args['menu'] ) && is_object( $exported_args['menu'] ) ) {
933 $exported_args['menu'] = $exported_args['menu']->term_id;
936 ksort( $exported_args );
937 $exported_args['args_hmac'] = $this->hash_nav_menu_args( $exported_args );
939 $args['customize_preview_nav_menus_args'] = $exported_args;
940 $this->preview_nav_menu_instance_args[ $exported_args['args_hmac'] ] = $exported_args;
945 * Prepares wp_nav_menu() calls for partial refresh.
947 * Injects attributes into container element.
954 * @param string $nav_menu_content The HTML content for the navigation menu.
955 * @param object $args An object containing wp_nav_menu() arguments.
958 public function filter_wp_nav_menu( $nav_menu_content, $args ) {
959 if ( isset( $args->customize_preview_nav_menus_args['can_partial_refresh'] ) && $args->customize_preview_nav_menus_args['can_partial_refresh'] ) {
960 $attributes = sprintf( ' data-customize-partial-id="%s"', esc_attr( 'nav_menu_instance[' . $args->customize_preview_nav_menus_args['args_hmac'] . ']' ) );
961 $attributes .= ' data-customize-partial-type="nav_menu_instance"';
962 $attributes .= sprintf( ' data-customize-partial-placement-context="%s"', esc_attr( wp_json_encode( $args->customize_preview_nav_menus_args ) ) );
963 $nav_menu_content = preg_replace( '#^(<\w+)#', '$1 ' . $attributes, $nav_menu_content, 1 );
965 return $nav_menu_content;
969 * Hashes (hmac) the nav menu arguments to ensure they are not tampered with when
970 * submitted in the Ajax request.
972 * Note that the array is expected to be pre-sorted.
977 * @param array $args The arguments to hash.
978 * @return string Hashed nav menu arguments.
980 public function hash_nav_menu_args( $args ) {
981 return wp_hash( serialize( $args ) );
985 * Enqueue scripts for the Customizer preview.
990 public function customize_preview_enqueue_deps() {
991 wp_enqueue_script( 'customize-preview-nav-menus' ); // Note that we have overridden this.
992 wp_enqueue_style( 'customize-preview' );
996 * Exports data from PHP to JS.
1001 public function export_preview_data() {
1003 // Why not wp_localize_script? Because we're not localizing, and it forces values into strings.
1005 'navMenuInstanceArgs' => $this->preview_nav_menu_instance_args,
1007 printf( '<script>var _wpCustomizePreviewNavMenusExports = %s;</script>', wp_json_encode( $exports ) );
1011 * Export any wp_nav_menu() calls during the rendering of any partials.
1016 * @param array $response Response.
1017 * @return array Response.
1019 public function export_partial_rendered_nav_menu_instances( $response ) {
1020 $response['nav_menu_instance_args'] = $this->preview_nav_menu_instance_args;
1025 * Render a specific menu via wp_nav_menu() using the supplied arguments.
1030 * @see wp_nav_menu()
1032 * @param WP_Customize_Partial $partial Partial.
1033 * @param array $nav_menu_args Nav menu args supplied as container context.
1034 * @return string|false
1036 public function render_nav_menu_partial( $partial, $nav_menu_args ) {
1039 if ( ! isset( $nav_menu_args['args_hmac'] ) ) {
1040 // Error: missing_args_hmac.
1044 $nav_menu_args_hmac = $nav_menu_args['args_hmac'];
1045 unset( $nav_menu_args['args_hmac'] );
1047 ksort( $nav_menu_args );
1048 if ( ! hash_equals( $this->hash_nav_menu_args( $nav_menu_args ), $nav_menu_args_hmac ) ) {
1049 // Error: args_hmac_mismatch.
1054 wp_nav_menu( $nav_menu_args );
1055 $content = ob_get_clean();