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 add_action( 'wp_ajax_load-available-menu-items-customizer', array( $this, 'ajax_load_available_items' ) );
52 add_action( 'wp_ajax_search-available-menu-items-customizer', array( $this, 'ajax_search_available_items' ) );
53 add_action( 'customize_controls_enqueue_scripts', array( $this, 'enqueue_scripts' ) );
55 // Needs to run after core Navigation section is set up.
56 add_action( 'customize_register', array( $this, 'customize_register' ), 11 );
58 add_filter( 'customize_dynamic_setting_args', array( $this, 'filter_dynamic_setting_args' ), 10, 2 );
59 add_filter( 'customize_dynamic_setting_class', array( $this, 'filter_dynamic_setting_class' ), 10, 3 );
60 add_action( 'customize_controls_print_footer_scripts', array( $this, 'print_templates' ) );
61 add_action( 'customize_controls_print_footer_scripts', array( $this, 'available_items_template' ) );
62 add_action( 'customize_preview_init', array( $this, 'customize_preview_init' ) );
66 * Ajax handler for loading available menu items.
71 public function ajax_load_available_items() {
72 check_ajax_referer( 'customize-menus', 'customize-menus-nonce' );
74 if ( ! current_user_can( 'edit_theme_options' ) ) {
78 if ( empty( $_POST['type'] ) || empty( $_POST['object'] ) ) {
79 wp_send_json_error( 'nav_menus_missing_type_or_object_parameter' );
82 $type = sanitize_key( $_POST['type'] );
83 $object = sanitize_key( $_POST['object'] );
84 $page = empty( $_POST['page'] ) ? 0 : absint( $_POST['page'] );
85 $items = $this->load_available_items_query( $type, $object, $page );
87 if ( is_wp_error( $items ) ) {
88 wp_send_json_error( $items->get_error_code() );
90 wp_send_json_success( array( 'items' => $items ) );
95 * Performs the post_type and taxonomy queries for loading available menu items.
100 * @param string $type Optional. Accepts any custom object type and has built-in support for
101 * 'post_type' and 'taxonomy'. Default is 'post_type'.
102 * @param string $object Optional. Accepts any registered taxonomy or post type name. Default is 'page'.
103 * @param int $page Optional. The page number used to generate the query offset. Default is '0'.
104 * @return WP_Error|array Returns either a WP_Error object or an array of menu items.
106 public function load_available_items_query( $type = 'post_type', $object = 'page', $page = 0 ) {
109 if ( 'post_type' === $type ) {
110 $post_type = get_post_type_object( $object );
111 if ( ! $post_type ) {
112 return new WP_Error( 'nav_menus_invalid_post_type' );
115 if ( 0 === $page && 'page' === $object ) {
116 // Add "Home" link. Treat as a page, but switch to custom on add.
119 'title' => _x( 'Home', 'nav menu home label' ),
121 'type_label' => __( 'Custom Link' ),
125 } elseif ( 'post' !== $object && 0 === $page && $post_type->has_archive ) {
126 // Add a post type archive link.
128 'id' => $object . '-archive',
129 'title' => $post_type->labels->archives,
130 'type' => 'post_type_archive',
131 'type_label' => __( 'Post Type Archive' ),
133 'url' => get_post_type_archive_link( $object ),
137 $posts = get_posts( array(
139 'offset' => 10 * $page,
142 'post_type' => $object,
144 foreach ( $posts as $post ) {
145 $post_title = $post->post_title;
146 if ( '' === $post_title ) {
147 /* translators: %d: ID of a post */
148 $post_title = sprintf( __( '#%d (no title)' ), $post->ID );
151 'id' => "post-{$post->ID}",
152 'title' => html_entity_decode( $post_title, ENT_QUOTES, get_bloginfo( 'charset' ) ),
153 'type' => 'post_type',
154 'type_label' => get_post_type_object( $post->post_type )->labels->singular_name,
155 'object' => $post->post_type,
156 'object_id' => intval( $post->ID ),
157 'url' => get_permalink( intval( $post->ID ) ),
160 } elseif ( 'taxonomy' === $type ) {
161 $terms = get_terms( $object, array(
164 'hide_empty' => false,
168 'offset' => 10 * $page,
170 'orderby' => 'count',
171 'pad_counts' => false,
173 if ( is_wp_error( $terms ) ) {
177 foreach ( $terms as $term ) {
179 'id' => "term-{$term->term_id}",
180 'title' => html_entity_decode( $term->name, ENT_QUOTES, get_bloginfo( 'charset' ) ),
181 'type' => 'taxonomy',
182 'type_label' => get_taxonomy( $term->taxonomy )->labels->singular_name,
183 'object' => $term->taxonomy,
184 'object_id' => intval( $term->term_id ),
185 'url' => get_term_link( intval( $term->term_id ), $term->taxonomy ),
191 * Filter the available menu items.
195 * @param array $items The array of menu items.
196 * @param string $type The object type.
197 * @param string $object The object name.
198 * @param int $page The current page number.
200 $items = apply_filters( 'customize_nav_menu_available_items', $items, $type, $object, $page );
206 * Ajax handler for searching available menu items.
211 public function ajax_search_available_items() {
212 check_ajax_referer( 'customize-menus', 'customize-menus-nonce' );
214 if ( ! current_user_can( 'edit_theme_options' ) ) {
218 if ( empty( $_POST['search'] ) ) {
219 wp_send_json_error( 'nav_menus_missing_search_parameter' );
222 $p = isset( $_POST['page'] ) ? absint( $_POST['page'] ) : 0;
227 $s = sanitize_text_field( wp_unslash( $_POST['search'] ) );
228 $items = $this->search_available_items_query( array( 'pagenum' => $p, 's' => $s ) );
230 if ( empty( $items ) ) {
231 wp_send_json_error( array( 'message' => __( 'No results found.' ) ) );
233 wp_send_json_success( array( 'items' => $items ) );
238 * Performs post queries for available-item searching.
240 * Based on WP_Editor::wp_link_query().
245 * @param array $args Optional. Accepts 'pagenum' and 's' (search) arguments.
246 * @return array Menu items.
248 public function search_available_items_query( $args = array() ) {
251 $post_type_objects = get_post_types( array( 'show_in_nav_menus' => true ), 'objects' );
253 'post_type' => array_keys( $post_type_objects ),
254 'suppress_filters' => true,
255 'update_post_term_cache' => false,
256 'update_post_meta_cache' => false,
257 'post_status' => 'publish',
258 'posts_per_page' => 20,
261 $args['pagenum'] = isset( $args['pagenum'] ) ? absint( $args['pagenum'] ) : 1;
262 $query['offset'] = $args['pagenum'] > 1 ? $query['posts_per_page'] * ( $args['pagenum'] - 1 ) : 0;
264 if ( isset( $args['s'] ) ) {
265 $query['s'] = $args['s'];
269 $get_posts = new WP_Query( $query );
271 // Check if any posts were found.
272 if ( $get_posts->post_count ) {
273 foreach ( $get_posts->posts as $post ) {
274 $post_title = $post->post_title;
275 if ( '' === $post_title ) {
276 /* translators: %d: ID of a post */
277 $post_title = sprintf( __( '#%d (no title)' ), $post->ID );
280 'id' => 'post-' . $post->ID,
281 'title' => html_entity_decode( $post_title, ENT_QUOTES, get_bloginfo( 'charset' ) ),
282 'type' => 'post_type',
283 'type_label' => $post_type_objects[ $post->post_type ]->labels->singular_name,
284 'object' => $post->post_type,
285 'object_id' => intval( $post->ID ),
286 'url' => get_permalink( intval( $post->ID ) ),
291 // Query taxonomy terms.
292 $taxonomies = get_taxonomies( array( 'show_in_nav_menus' => true ), 'names' );
293 $terms = get_terms( $taxonomies, array(
294 'name__like' => $args['s'],
296 'offset' => 20 * ($args['pagenum'] - 1),
299 // Check if any taxonomies were found.
300 if ( ! empty( $terms ) ) {
301 foreach ( $terms as $term ) {
303 'id' => 'term-' . $term->term_id,
304 'title' => html_entity_decode( $term->name, ENT_QUOTES, get_bloginfo( 'charset' ) ),
305 'type' => 'taxonomy',
306 'type_label' => get_taxonomy( $term->taxonomy )->labels->singular_name,
307 'object' => $term->taxonomy,
308 'object_id' => intval( $term->term_id ),
309 'url' => get_term_link( intval( $term->term_id ), $term->taxonomy ),
318 * Enqueue scripts and styles for Customizer pane.
323 public function enqueue_scripts() {
324 wp_enqueue_style( 'customize-nav-menus' );
325 wp_enqueue_script( 'customize-nav-menus' );
327 $temp_nav_menu_setting = new WP_Customize_Nav_Menu_Setting( $this->manager, 'nav_menu[-1]' );
328 $temp_nav_menu_item_setting = new WP_Customize_Nav_Menu_Item_Setting( $this->manager, 'nav_menu_item[-1]' );
332 'nonce' => wp_create_nonce( 'customize-menus' ),
333 'allMenus' => wp_get_nav_menus(),
334 'itemTypes' => $this->available_item_types(),
336 'untitled' => _x( '(no label)', 'missing menu item navigation label' ),
337 'unnamed' => _x( '(unnamed)', 'Missing menu name.' ),
338 'custom_label' => __( 'Custom Link' ),
339 /* translators: %s: menu location slug */
340 'menuLocation' => _x( '(Currently set to: %s)', 'menu' ),
341 'menuNameLabel' => __( 'Menu Name' ),
342 'itemAdded' => __( 'Menu item added' ),
343 'itemDeleted' => __( 'Menu item deleted' ),
344 'menuAdded' => __( 'Menu created' ),
345 'menuDeleted' => __( 'Menu deleted' ),
346 'movedUp' => __( 'Menu item moved up' ),
347 'movedDown' => __( 'Menu item moved down' ),
348 'movedLeft' => __( 'Menu item moved out of submenu' ),
349 'movedRight' => __( 'Menu item is now a sub-item' ),
350 /* translators: ▸ is the unicode right-pointing triangle, and %s is the section title in the Customizer */
351 'customizingMenus' => sprintf( __( 'Customizing ▸ %s' ), esc_html( $this->manager->get_panel( 'nav_menus' )->title ) ),
352 /* translators: %s: title of menu item which is invalid */
353 'invalidTitleTpl' => __( '%s (Invalid)' ),
354 /* translators: %s: title of menu item in draft status */
355 'pendingTitleTpl' => __( '%s (Pending)' ),
356 'itemsFound' => __( 'Number of items found: %d' ),
357 'itemsFoundMore' => __( 'Additional items found: %d' ),
358 'itemsLoadingMore' => __( 'Loading more results... please wait.' ),
359 'reorderModeOn' => __( 'Reorder mode enabled' ),
360 'reorderModeOff' => __( 'Reorder mode closed' ),
361 'reorderLabelOn' => esc_attr__( 'Reorder menu items' ),
362 'reorderLabelOff' => esc_attr__( 'Close reorder mode' ),
364 'menuItemTransport' => 'postMessage',
365 'phpIntMax' => PHP_INT_MAX,
366 'defaultSettingValues' => array(
367 'nav_menu' => $temp_nav_menu_setting->default,
368 'nav_menu_item' => $temp_nav_menu_item_setting->default,
372 $data = sprintf( 'var _wpCustomizeNavMenusSettings = %s;', wp_json_encode( $settings ) );
373 wp_scripts()->add_data( 'customize-nav-menus', 'data', $data );
375 // This is copied from nav-menus.php, and it has an unfortunate object name of `menus`.
376 $nav_menus_l10n = array(
377 'oneThemeLocationNoMenus' => null,
378 'moveUp' => __( 'Move up one' ),
379 'moveDown' => __( 'Move down one' ),
380 'moveToTop' => __( 'Move to the top' ),
381 /* translators: %s: previous item name */
382 'moveUnder' => __( 'Move under %s' ),
383 /* translators: %s: previous item name */
384 'moveOutFrom' => __( 'Move out from under %s' ),
385 /* translators: %s: previous item name */
386 'under' => __( 'Under %s' ),
387 /* translators: %s: previous item name */
388 'outFrom' => __( 'Out from under %s' ),
389 /* translators: 1: item name, 2: item position, 3: total number of items */
390 'menuFocus' => __( '%1$s. Menu item %2$d of %3$d.' ),
391 /* translators: 1: item name, 2: item position, 3: parent item name */
392 'subMenuFocus' => __( '%1$s. Sub item number %2$d under %3$s.' ),
394 wp_localize_script( 'nav-menu', 'menus', $nav_menus_l10n );
398 * Filter a dynamic setting's constructor args.
400 * For a dynamic setting to be registered, this filter must be employed
401 * to override the default false value with an array of args to pass to
402 * the WP_Customize_Setting constructor.
407 * @param false|array $setting_args The arguments to the WP_Customize_Setting constructor.
408 * @param string $setting_id ID for dynamic setting, usually coming from `$_POST['customized']`.
409 * @return array|false
411 public function filter_dynamic_setting_args( $setting_args, $setting_id ) {
412 if ( preg_match( WP_Customize_Nav_Menu_Setting::ID_PATTERN, $setting_id ) ) {
413 $setting_args = array(
414 'type' => WP_Customize_Nav_Menu_Setting::TYPE,
416 } elseif ( preg_match( WP_Customize_Nav_Menu_Item_Setting::ID_PATTERN, $setting_id ) ) {
417 $setting_args = array(
418 'type' => WP_Customize_Nav_Menu_Item_Setting::TYPE,
421 return $setting_args;
425 * Allow non-statically created settings to be constructed with custom WP_Customize_Setting subclass.
430 * @param string $setting_class WP_Customize_Setting or a subclass.
431 * @param string $setting_id ID for dynamic setting, usually coming from `$_POST['customized']`.
432 * @param array $setting_args WP_Customize_Setting or a subclass.
435 public function filter_dynamic_setting_class( $setting_class, $setting_id, $setting_args ) {
436 unset( $setting_id );
438 if ( ! empty( $setting_args['type'] ) && WP_Customize_Nav_Menu_Setting::TYPE === $setting_args['type'] ) {
439 $setting_class = 'WP_Customize_Nav_Menu_Setting';
440 } elseif ( ! empty( $setting_args['type'] ) && WP_Customize_Nav_Menu_Item_Setting::TYPE === $setting_args['type'] ) {
441 $setting_class = 'WP_Customize_Nav_Menu_Item_Setting';
443 return $setting_class;
447 * Add the customizer settings and controls.
452 public function customize_register() {
454 // Require JS-rendered control types.
455 $this->manager->register_panel_type( 'WP_Customize_Nav_Menus_Panel' );
456 $this->manager->register_control_type( 'WP_Customize_Nav_Menu_Control' );
457 $this->manager->register_control_type( 'WP_Customize_Nav_Menu_Name_Control' );
458 $this->manager->register_control_type( 'WP_Customize_Nav_Menu_Auto_Add_Control' );
459 $this->manager->register_control_type( 'WP_Customize_Nav_Menu_Item_Control' );
461 // Create a panel for Menus.
462 $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>';
463 if ( current_theme_supports( 'widgets' ) ) {
464 $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>';
466 $description .= '<p>' . __( 'Menus can be displayed in locations defined by your theme.' ) . '</p>';
468 $this->manager->add_panel( new WP_Customize_Nav_Menus_Panel( $this->manager, 'nav_menus', array(
469 'title' => __( 'Menus' ),
470 'description' => $description,
472 // 'theme_supports' => 'menus|widgets', @todo allow multiple theme supports
474 $menus = wp_get_nav_menus();
477 $locations = get_registered_nav_menus();
478 $num_locations = count( array_keys( $locations ) );
479 if ( 1 == $num_locations ) {
480 $description = '<p>' . __( 'Your theme supports one menu. Select which menu you would like to use.' );
482 $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 ) );
484 $description .= '</p><p>' . __( 'You can also place menus in widget areas with the Custom Menu widget.' ) . '</p>';
486 $this->manager->add_section( 'menu_locations', array(
487 'title' => __( 'Menu Locations' ),
488 'panel' => 'nav_menus',
490 'description' => $description,
493 $choices = array( '0' => __( '— Select —' ) );
494 foreach ( $menus as $menu ) {
495 $choices[ $menu->term_id ] = wp_html_excerpt( $menu->name, 40, '…' );
498 foreach ( $locations as $location => $description ) {
499 $setting_id = "nav_menu_locations[{$location}]";
501 $setting = $this->manager->get_setting( $setting_id );
503 $setting->transport = 'postMessage';
504 remove_filter( "customize_sanitize_{$setting_id}", 'absint' );
505 add_filter( "customize_sanitize_{$setting_id}", array( $this, 'intval_base10' ) );
507 $this->manager->add_setting( $setting_id, array(
508 'sanitize_callback' => array( $this, 'intval_base10' ),
509 'theme_supports' => 'menus',
510 'type' => 'theme_mod',
511 'transport' => 'postMessage',
516 $this->manager->add_control( new WP_Customize_Nav_Menu_Location_Control( $this->manager, $setting_id, array(
517 'label' => $description,
518 'location_id' => $location,
519 'section' => 'menu_locations',
520 'choices' => $choices,
524 // Register each menu as a Customizer section, and add each menu item to each menu.
525 foreach ( $menus as $menu ) {
526 $menu_id = $menu->term_id;
528 // Create a section for each menu.
529 $section_id = 'nav_menu[' . $menu_id . ']';
530 $this->manager->add_section( new WP_Customize_Nav_Menu_Section( $this->manager, $section_id, array(
531 'title' => html_entity_decode( $menu->name, ENT_QUOTES, get_bloginfo( 'charset' ) ),
533 'panel' => 'nav_menus',
536 $nav_menu_setting_id = 'nav_menu[' . $menu_id . ']';
537 $this->manager->add_setting( new WP_Customize_Nav_Menu_Setting( $this->manager, $nav_menu_setting_id ) );
539 // Add the menu contents.
540 $menu_items = (array) wp_get_nav_menu_items( $menu_id );
542 foreach ( array_values( $menu_items ) as $i => $item ) {
544 // Create a setting for each menu item (which doesn't actually manage data, currently).
545 $menu_item_setting_id = 'nav_menu_item[' . $item->ID . ']';
547 $value = (array) $item;
548 $value['nav_menu_term_id'] = $menu_id;
549 $this->manager->add_setting( new WP_Customize_Nav_Menu_Item_Setting( $this->manager, $menu_item_setting_id, array(
553 // Create a control for each menu item.
554 $this->manager->add_control( new WP_Customize_Nav_Menu_Item_Control( $this->manager, $menu_item_setting_id, array(
555 'label' => $item->title,
556 'section' => $section_id,
557 'priority' => 10 + $i,
561 // Note: other controls inside of this section get added dynamically in JS via the MenuSection.ready() function.
564 // Add the add-new-menu section and controls.
565 $this->manager->add_section( new WP_Customize_New_Menu_Section( $this->manager, 'add_menu', array(
566 'title' => __( 'Add a Menu' ),
567 'panel' => 'nav_menus',
571 $this->manager->add_setting( 'new_menu_name', array(
572 'type' => 'new_menu',
574 'transport' => 'postMessage',
577 $this->manager->add_control( 'new_menu_name', array(
579 'section' => 'add_menu',
581 'input_attrs' => array(
582 'class' => 'menu-name-field',
583 'placeholder' => __( 'New menu name' ),
587 $this->manager->add_setting( 'create_new_menu', array(
588 'type' => 'new_menu',
591 $this->manager->add_control( new WP_Customize_New_Menu_Control( $this->manager, 'create_new_menu', array(
592 'section' => 'add_menu',
597 * Get the base10 intval.
599 * This is used as a setting's sanitize_callback; we can't use just plain
600 * intval because the second argument is not what intval() expects.
605 * @param mixed $value Number to convert.
606 * @return int Integer.
608 public function intval_base10( $value ) {
609 return intval( $value, 10 );
613 * Return an array of all the available item types.
618 * @return array The available menu item types.
620 public function available_item_types() {
621 $item_types = array();
623 $post_types = get_post_types( array( 'show_in_nav_menus' => true ), 'objects' );
625 foreach ( $post_types as $slug => $post_type ) {
626 $item_types[] = array(
627 'title' => $post_type->labels->name,
628 'type' => 'post_type',
629 'object' => $post_type->name,
634 $taxonomies = get_taxonomies( array( 'show_in_nav_menus' => true ), 'objects' );
636 foreach ( $taxonomies as $slug => $taxonomy ) {
637 if ( 'post_format' === $taxonomy && ! current_theme_supports( 'post-formats' ) ) {
640 $item_types[] = array(
641 'title' => $taxonomy->labels->name,
642 'type' => 'taxonomy',
643 'object' => $taxonomy->name,
649 * Filter the available menu item types.
653 * @param array $item_types Custom menu item types.
655 $item_types = apply_filters( 'customize_nav_menu_available_item_types', $item_types );
661 * Print the JavaScript templates used to render Menu Customizer components.
663 * Templates are imported into the JS use wp.template.
668 public function print_templates() {
670 <script type="text/html" id="tmpl-available-menu-item">
671 <li id="menu-item-tpl-{{ data.id }}" class="menu-item-tpl" data-menu-item-id="{{ data.id }}">
672 <div class="menu-item-bar">
673 <div class="menu-item-handle">
674 <span class="item-type" aria-hidden="true">{{ data.type_label }}</span>
675 <span class="item-title" aria-hidden="true">
676 <span class="menu-item-title<# if ( ! data.title ) { #> no-title<# } #>">{{ data.title || wp.customize.Menus.data.l10n.untitled }}</span>
678 <button type="button" class="button-link item-add">
679 <span class="screen-reader-text"><?php
680 /* translators: 1: Title of a menu item, 2: Type of a menu item */
681 printf( __( 'Add to menu: %1$s (%2$s)' ), '{{ data.title || wp.customize.Menus.data.l10n.untitled }}', '{{ data.type_label }}' );
689 <script type="text/html" id="tmpl-menu-item-reorder-nav">
690 <div class="menu-item-reorder-nav">
693 '<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>',
696 __( 'Move one level up' ),
697 __( 'Move one level down' )
706 * Print the html template used to render the add-menu-item frame.
711 public function available_items_template() {
713 <div id="available-menu-items" class="accordion-container">
714 <div class="customize-section-title">
715 <button type="button" class="customize-section-back" tabindex="-1">
716 <span class="screen-reader-text"><?php _e( 'Back' ); ?></span>
719 <span class="customize-action">
721 /* translators: ▸ is the unicode right-pointing triangle, and %s is the section title in the Customizer */
722 printf( __( 'Customizing ▸ %s' ), esc_html( $this->manager->get_panel( 'nav_menus' )->title ) );
725 <?php _e( 'Add Menu Items' ); ?>
728 <div id="available-menu-items-search" class="accordion-section cannot-expand">
729 <div class="accordion-section-title">
730 <label class="screen-reader-text" for="menu-items-search"><?php _e( 'Search Menu Items' ); ?></label>
731 <input type="text" id="menu-items-search" placeholder="<?php esc_attr_e( 'Search menu items…' ) ?>" aria-describedby="menu-items-search-desc" />
732 <p class="screen-reader-text" id="menu-items-search-desc"><?php _e( 'The search results will be updated as you type.' ); ?></p>
733 <span class="spinner"></span>
734 <span class="clear-results"><span class="screen-reader-text"><?php _e( 'Clear Results' ); ?></span></span>
736 <ul class="accordion-section-content" data-type="search"></ul>
738 <div id="new-custom-menu-item" class="accordion-section">
739 <h4 class="accordion-section-title" role="presentation">
740 <?php _e( 'Custom Links' ); ?>
741 <button type="button" class="button-link" aria-expanded="false">
742 <span class="screen-reader-text"><?php _e( 'Toggle section: Custom Links' ); ?></span>
743 <span class="toggle-indicator" aria-hidden="true"></span>
746 <div class="accordion-section-content">
747 <input type="hidden" value="custom" id="custom-menu-item-type" name="menu-item[-1][menu-item-type]" />
748 <p id="menu-item-url-wrap">
749 <label class="howto" for="custom-menu-item-url">
750 <span><?php _e( 'URL' ); ?></span>
751 <input id="custom-menu-item-url" name="menu-item[-1][menu-item-url]" type="text" class="code menu-item-textbox" value="http://">
754 <p id="menu-item-name-wrap">
755 <label class="howto" for="custom-menu-item-name">
756 <span><?php _e( 'Link Text' ); ?></span>
757 <input id="custom-menu-item-name" name="menu-item[-1][menu-item-title]" type="text" class="regular-text menu-item-textbox">
760 <p class="button-controls">
761 <span class="add-to-menu">
762 <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">
763 <span class="spinner"></span>
769 // Containers for per-post-type item browsing; items added with JS.
770 foreach ( $this->available_item_types() as $available_item_type ) {
771 $id = sprintf( 'available-menu-items-%s-%s', $available_item_type['type'], $available_item_type['object'] );
773 <div id="<?php echo esc_attr( $id ); ?>" class="accordion-section">
774 <h4 class="accordion-section-title" role="presentation">
775 <?php echo esc_html( $available_item_type['title'] ); ?>
776 <span class="spinner"></span>
777 <span class="no-items"><?php _e( 'No items' ); ?></span>
778 <button type="button" class="button-link" aria-expanded="false">
779 <span class="screen-reader-text"><?php
780 /* translators: %s: Title of a section with menu items */
781 printf( __( 'Toggle section: %s' ), esc_html( $available_item_type['title'] ) ); ?></span>
782 <span class="toggle-indicator" aria-hidden="true"></span>
785 <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>
790 </div><!-- #available-menu-items -->
794 // Start functionality specific to partial-refresh of menu changes in Customizer preview.
795 const RENDER_AJAX_ACTION = 'customize_render_menu_partial';
796 const RENDER_NONCE_POST_KEY = 'render-menu-nonce';
797 const RENDER_QUERY_VAR = 'wp_customize_menu_render';
800 * The number of wp_nav_menu() calls which have happened in the preview.
806 public $preview_nav_menu_instance_number = 0;
809 * Nav menu args used for each instance.
815 public $preview_nav_menu_instance_args = array();
818 * Add hooks for the Customizer preview.
823 public function customize_preview_init() {
824 add_action( 'template_redirect', array( $this, 'render_menu' ) );
825 add_action( 'wp_enqueue_scripts', array( $this, 'customize_preview_enqueue_deps' ) );
827 if ( ! isset( $_REQUEST[ self::RENDER_QUERY_VAR ] ) ) {
828 add_filter( 'wp_nav_menu_args', array( $this, 'filter_wp_nav_menu_args' ), 1000 );
829 add_filter( 'wp_nav_menu', array( $this, 'filter_wp_nav_menu' ), 10, 2 );
834 * Keep track of the arguments that are being passed to wp_nav_menu().
841 * @param array $args An array containing wp_nav_menu() arguments.
842 * @return array Arguments.
844 public function filter_wp_nav_menu_args( $args ) {
845 $this->preview_nav_menu_instance_number += 1;
846 $args['instance_number'] = $this->preview_nav_menu_instance_number;
848 $can_partial_refresh = (
849 ! empty( $args['echo'] )
851 ( empty( $args['fallback_cb'] ) || is_string( $args['fallback_cb'] ) )
853 ( empty( $args['walker'] ) || is_string( $args['walker'] ) )
856 ! empty( $args['theme_location'] )
858 ( ! empty( $args['menu'] ) && ( is_numeric( $args['menu'] ) || is_object( $args['menu'] ) ) )
861 $args['can_partial_refresh'] = $can_partial_refresh;
863 $hashed_args = $args;
865 if ( ! $can_partial_refresh ) {
866 $hashed_args['fallback_cb'] = '';
867 $hashed_args['walker'] = '';
870 // Replace object menu arg with a term_id menu arg, as this exports better to JS and is easier to compare hashes.
871 if ( ! empty( $hashed_args['menu'] ) && is_object( $hashed_args['menu'] ) ) {
872 $hashed_args['menu'] = $hashed_args['menu']->term_id;
875 ksort( $hashed_args );
876 $hashed_args['args_hash'] = $this->hash_nav_menu_args( $hashed_args );
878 $this->preview_nav_menu_instance_args[ $this->preview_nav_menu_instance_number ] = $hashed_args;
883 * Prepare wp_nav_menu() calls for partial refresh. Wraps output in container for refreshing.
890 * @param string $nav_menu_content The HTML content for the navigation menu.
891 * @param object $args An object containing wp_nav_menu() arguments.
894 public function filter_wp_nav_menu( $nav_menu_content, $args ) {
895 if ( ! empty( $args->can_partial_refresh ) && ! empty( $args->instance_number ) ) {
896 $nav_menu_content = preg_replace(
898 sprintf( 'partial-refreshable-nav-menu partial-refreshable-nav-menu-%1$d ', $args->instance_number ),
900 1 // Only update the class on the first element found, the menu container.
903 return $nav_menu_content;
907 * Hash (hmac) the arguments with the nonce and secret auth key to ensure they
908 * are not tampered with when submitted in the Ajax request.
913 * @param array $args The arguments to hash.
916 public function hash_nav_menu_args( $args ) {
917 return wp_hash( wp_create_nonce( self::RENDER_AJAX_ACTION ) . serialize( $args ) );
921 * Enqueue scripts for the Customizer preview.
926 public function customize_preview_enqueue_deps() {
927 wp_enqueue_script( 'customize-preview-nav-menus' );
928 wp_enqueue_style( 'customize-preview' );
930 add_action( 'wp_print_footer_scripts', array( $this, 'export_preview_data' ) );
934 * Export data from PHP to JS.
939 public function export_preview_data() {
941 // Why not wp_localize_script? Because we're not localizing, and it forces values into strings.
943 'renderQueryVar' => self::RENDER_QUERY_VAR,
944 'renderNonceValue' => wp_create_nonce( self::RENDER_AJAX_ACTION ),
945 'renderNoncePostKey' => self::RENDER_NONCE_POST_KEY,
946 'requestUri' => empty( $_SERVER['REQUEST_URI'] ) ? home_url( '/' ) : esc_url_raw( wp_unslash( $_SERVER['REQUEST_URI'] ) ),
948 'stylesheet' => $this->manager->get_stylesheet(),
949 'active' => $this->manager->is_theme_active(),
951 'previewCustomizeNonce' => wp_create_nonce( 'preview-customize_' . $this->manager->get_stylesheet() ),
952 'navMenuInstanceArgs' => $this->preview_nav_menu_instance_args,
955 printf( '<script>var _wpCustomizePreviewNavMenusExports = %s;</script>', wp_json_encode( $exports ) );
959 * Render a specific menu via wp_nav_menu() using the supplied arguments.
966 public function render_menu() {
967 if ( empty( $_POST[ self::RENDER_QUERY_VAR ] ) ) {
971 $this->manager->remove_preview_signature();
973 if ( empty( $_POST[ self::RENDER_NONCE_POST_KEY ] ) ) {
974 wp_send_json_error( 'missing_nonce_param' );
977 if ( ! is_customize_preview() ) {
978 wp_send_json_error( 'expected_customize_preview' );
981 if ( ! check_ajax_referer( self::RENDER_AJAX_ACTION, self::RENDER_NONCE_POST_KEY, false ) ) {
982 wp_send_json_error( 'nonce_check_fail' );
985 if ( ! current_user_can( 'edit_theme_options' ) ) {
986 wp_send_json_error( 'unauthorized' );
989 if ( ! isset( $_POST['wp_nav_menu_args'] ) ) {
990 wp_send_json_error( 'missing_param' );
993 if ( ! isset( $_POST['wp_nav_menu_args_hash'] ) ) {
994 wp_send_json_error( 'missing_param' );
997 $wp_nav_menu_args = json_decode( wp_unslash( $_POST['wp_nav_menu_args'] ), true );
998 if ( ! is_array( $wp_nav_menu_args ) ) {
999 wp_send_json_error( 'wp_nav_menu_args_not_array' );
1002 $wp_nav_menu_args_hash = sanitize_text_field( wp_unslash( $_POST['wp_nav_menu_args_hash'] ) );
1003 if ( ! hash_equals( $this->hash_nav_menu_args( $wp_nav_menu_args ), $wp_nav_menu_args_hash ) ) {
1004 wp_send_json_error( 'wp_nav_menu_args_hash_mismatch' );
1007 $wp_nav_menu_args['echo'] = false;
1008 wp_send_json_success( wp_nav_menu( $wp_nav_menu_args ) );