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 // See https://github.com/xwp/wp-customize-snapshots/blob/962586659688a5b1fd9ae93618b7ce2d4e7a421c/php/class-customize-snapshot-manager.php#L469-L499
52 add_action( 'customize_register', array( $this, 'customize_register' ), 11 );
53 add_filter( 'customize_dynamic_setting_args', array( $this, 'filter_dynamic_setting_args' ), 10, 2 );
54 add_filter( 'customize_dynamic_setting_class', array( $this, 'filter_dynamic_setting_class' ), 10, 3 );
56 // Skip remaining hooks when the user can't manage nav menus anyway.
57 if ( ! current_user_can( 'edit_theme_options' ) ) {
61 add_filter( 'customize_refresh_nonces', array( $this, 'filter_nonces' ) );
62 add_action( 'wp_ajax_load-available-menu-items-customizer', array( $this, 'ajax_load_available_items' ) );
63 add_action( 'wp_ajax_search-available-menu-items-customizer', array( $this, 'ajax_search_available_items' ) );
64 add_action( 'wp_ajax_customize-nav-menus-insert-auto-draft', array( $this, 'ajax_insert_auto_draft_post' ) );
65 add_action( 'customize_controls_enqueue_scripts', array( $this, 'enqueue_scripts' ) );
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' ) );
69 add_action( 'customize_preview_init', array( $this, 'make_auto_draft_status_previewable' ) );
70 add_action( 'customize_save_nav_menus_created_posts', array( $this, 'save_nav_menus_created_posts' ) );
72 // Selective Refresh partials.
73 add_filter( 'customize_dynamic_partial_args', array( $this, 'customize_dynamic_partial_args' ), 10, 2 );
77 * Adds a nonce for customizing menus.
82 * @param array $nonces Array of nonces.
83 * @return array $nonces Modified array of nonces.
85 public function filter_nonces( $nonces ) {
86 $nonces['customize-menus'] = wp_create_nonce( 'customize-menus' );
91 * Ajax handler for loading available menu items.
96 public function ajax_load_available_items() {
97 check_ajax_referer( 'customize-menus', 'customize-menus-nonce' );
99 if ( ! current_user_can( 'edit_theme_options' ) ) {
103 $all_items = array();
104 $item_types = array();
105 if ( isset( $_POST['item_types'] ) && is_array( $_POST['item_types'] ) ) {
106 $item_types = wp_unslash( $_POST['item_types'] );
107 } elseif ( isset( $_POST['type'] ) && isset( $_POST['object'] ) ) { // Back compat.
108 $item_types[] = array(
109 'type' => wp_unslash( $_POST['type'] ),
110 'object' => wp_unslash( $_POST['object'] ),
111 'page' => empty( $_POST['page'] ) ? 0 : absint( $_POST['page'] ),
114 wp_send_json_error( 'nav_menus_missing_type_or_object_parameter' );
117 foreach ( $item_types as $item_type ) {
118 if ( empty( $item_type['type'] ) || empty( $item_type['object'] ) ) {
119 wp_send_json_error( 'nav_menus_missing_type_or_object_parameter' );
121 $type = sanitize_key( $item_type['type'] );
122 $object = sanitize_key( $item_type['object'] );
123 $page = empty( $item_type['page'] ) ? 0 : absint( $item_type['page'] );
124 $items = $this->load_available_items_query( $type, $object, $page );
125 if ( is_wp_error( $items ) ) {
126 wp_send_json_error( $items->get_error_code() );
128 $all_items[ $item_type['type'] . ':' . $item_type['object'] ] = $items;
131 wp_send_json_success( array( 'items' => $all_items ) );
135 * Performs the post_type and taxonomy queries for loading available menu items.
140 * @param string $type Optional. Accepts any custom object type and has built-in support for
141 * 'post_type' and 'taxonomy'. Default is 'post_type'.
142 * @param string $object Optional. Accepts any registered taxonomy or post type name. Default is 'page'.
143 * @param int $page Optional. The page number used to generate the query offset. Default is '0'.
144 * @return WP_Error|array Returns either a WP_Error object or an array of menu items.
146 public function load_available_items_query( $type = 'post_type', $object = 'page', $page = 0 ) {
149 if ( 'post_type' === $type ) {
150 $post_type = get_post_type_object( $object );
151 if ( ! $post_type ) {
152 return new WP_Error( 'nav_menus_invalid_post_type' );
155 if ( 0 === $page && 'page' === $object ) {
156 // Add "Home" link. Treat as a page, but switch to custom on add.
159 'title' => _x( 'Home', 'nav menu home label' ),
161 'type_label' => __( 'Custom Link' ),
165 } elseif ( 'post' !== $object && 0 === $page && $post_type->has_archive ) {
166 // Add a post type archive link.
168 'id' => $object . '-archive',
169 'title' => $post_type->labels->archives,
170 'type' => 'post_type_archive',
171 'type_label' => __( 'Post Type Archive' ),
173 'url' => get_post_type_archive_link( $object ),
177 // Prepend posts with nav_menus_created_posts on first page.
179 if ( 0 === $page && $this->manager->get_setting( 'nav_menus_created_posts' ) ) {
180 foreach ( $this->manager->get_setting( 'nav_menus_created_posts' )->value() as $post_id ) {
181 $auto_draft_post = get_post( $post_id );
182 if ( $post_type->name === $auto_draft_post->post_type ) {
183 $posts[] = $auto_draft_post;
188 $posts = array_merge( $posts, get_posts( array(
190 'offset' => 10 * $page,
193 'post_type' => $object,
196 foreach ( $posts as $post ) {
197 $post_title = $post->post_title;
198 if ( '' === $post_title ) {
199 /* translators: %d: ID of a post */
200 $post_title = sprintf( __( '#%d (no title)' ), $post->ID );
203 'id' => "post-{$post->ID}",
204 'title' => html_entity_decode( $post_title, ENT_QUOTES, get_bloginfo( 'charset' ) ),
205 'type' => 'post_type',
206 'type_label' => get_post_type_object( $post->post_type )->labels->singular_name,
207 'object' => $post->post_type,
208 'object_id' => intval( $post->ID ),
209 'url' => get_permalink( intval( $post->ID ) ),
212 } elseif ( 'taxonomy' === $type ) {
213 $terms = get_terms( $object, array(
216 'hide_empty' => false,
220 'offset' => 10 * $page,
222 'orderby' => 'count',
223 'pad_counts' => false,
225 if ( is_wp_error( $terms ) ) {
229 foreach ( $terms as $term ) {
231 'id' => "term-{$term->term_id}",
232 'title' => html_entity_decode( $term->name, ENT_QUOTES, get_bloginfo( 'charset' ) ),
233 'type' => 'taxonomy',
234 'type_label' => get_taxonomy( $term->taxonomy )->labels->singular_name,
235 'object' => $term->taxonomy,
236 'object_id' => intval( $term->term_id ),
237 'url' => get_term_link( intval( $term->term_id ), $term->taxonomy ),
243 * Filters the available menu items.
247 * @param array $items The array of menu items.
248 * @param string $type The object type.
249 * @param string $object The object name.
250 * @param int $page The current page number.
252 $items = apply_filters( 'customize_nav_menu_available_items', $items, $type, $object, $page );
258 * Ajax handler for searching available menu items.
263 public function ajax_search_available_items() {
264 check_ajax_referer( 'customize-menus', 'customize-menus-nonce' );
266 if ( ! current_user_can( 'edit_theme_options' ) ) {
270 if ( empty( $_POST['search'] ) ) {
271 wp_send_json_error( 'nav_menus_missing_search_parameter' );
274 $p = isset( $_POST['page'] ) ? absint( $_POST['page'] ) : 0;
279 $s = sanitize_text_field( wp_unslash( $_POST['search'] ) );
280 $items = $this->search_available_items_query( array( 'pagenum' => $p, 's' => $s ) );
282 if ( empty( $items ) ) {
283 wp_send_json_error( array( 'message' => __( 'No results found.' ) ) );
285 wp_send_json_success( array( 'items' => $items ) );
290 * Performs post queries for available-item searching.
292 * Based on WP_Editor::wp_link_query().
297 * @param array $args Optional. Accepts 'pagenum' and 's' (search) arguments.
298 * @return array Menu items.
300 public function search_available_items_query( $args = array() ) {
303 $post_type_objects = get_post_types( array( 'show_in_nav_menus' => true ), 'objects' );
305 'post_type' => array_keys( $post_type_objects ),
306 'suppress_filters' => true,
307 'update_post_term_cache' => false,
308 'update_post_meta_cache' => false,
309 'post_status' => 'publish',
310 'posts_per_page' => 20,
313 $args['pagenum'] = isset( $args['pagenum'] ) ? absint( $args['pagenum'] ) : 1;
314 $query['offset'] = $args['pagenum'] > 1 ? $query['posts_per_page'] * ( $args['pagenum'] - 1 ) : 0;
316 if ( isset( $args['s'] ) ) {
317 $query['s'] = $args['s'];
322 // Prepend list of posts with nav_menus_created_posts search results on first page.
323 $nav_menus_created_posts_setting = $this->manager->get_setting( 'nav_menus_created_posts' );
324 if ( 1 === $args['pagenum'] && $nav_menus_created_posts_setting && count( $nav_menus_created_posts_setting ) > 0 ) {
325 $stub_post_query = new WP_Query( array_merge(
328 'post_status' => 'auto-draft',
329 'post__in' => $nav_menus_created_posts_setting->value(),
330 'posts_per_page' => -1,
333 $posts = array_merge( $posts, $stub_post_query->posts );
337 $get_posts = new WP_Query( $query );
338 $posts = array_merge( $posts, $get_posts->posts );
340 // Create items for posts.
341 foreach ( $posts as $post ) {
342 $post_title = $post->post_title;
343 if ( '' === $post_title ) {
344 /* translators: %d: ID of a post */
345 $post_title = sprintf( __( '#%d (no title)' ), $post->ID );
348 'id' => 'post-' . $post->ID,
349 'title' => html_entity_decode( $post_title, ENT_QUOTES, get_bloginfo( 'charset' ) ),
350 'type' => 'post_type',
351 'type_label' => $post_type_objects[ $post->post_type ]->labels->singular_name,
352 'object' => $post->post_type,
353 'object_id' => intval( $post->ID ),
354 'url' => get_permalink( intval( $post->ID ) ),
358 // Query taxonomy terms.
359 $taxonomies = get_taxonomies( array( 'show_in_nav_menus' => true ), 'names' );
360 $terms = get_terms( $taxonomies, array(
361 'name__like' => $args['s'],
363 'offset' => 20 * ($args['pagenum'] - 1),
366 // Check if any taxonomies were found.
367 if ( ! empty( $terms ) ) {
368 foreach ( $terms as $term ) {
370 'id' => 'term-' . $term->term_id,
371 'title' => html_entity_decode( $term->name, ENT_QUOTES, get_bloginfo( 'charset' ) ),
372 'type' => 'taxonomy',
373 'type_label' => get_taxonomy( $term->taxonomy )->labels->singular_name,
374 'object' => $term->taxonomy,
375 'object_id' => intval( $term->term_id ),
376 'url' => get_term_link( intval( $term->term_id ), $term->taxonomy ),
382 * Filters the available menu items during a search request.
386 * @param array $items The array of menu items.
387 * @param array $args Includes 'pagenum' and 's' (search) arguments.
389 $items = apply_filters( 'customize_nav_menu_searched_items', $items, $args );
395 * Enqueue scripts and styles for Customizer pane.
400 public function enqueue_scripts() {
401 wp_enqueue_style( 'customize-nav-menus' );
402 wp_enqueue_script( 'customize-nav-menus' );
404 $temp_nav_menu_setting = new WP_Customize_Nav_Menu_Setting( $this->manager, 'nav_menu[-1]' );
405 $temp_nav_menu_item_setting = new WP_Customize_Nav_Menu_Item_Setting( $this->manager, 'nav_menu_item[-1]' );
409 'allMenus' => wp_get_nav_menus(),
410 'itemTypes' => $this->available_item_types(),
412 'untitled' => _x( '(no label)', 'missing menu item navigation label' ),
413 'unnamed' => _x( '(unnamed)', 'Missing menu name.' ),
414 'custom_label' => __( 'Custom Link' ),
415 'page_label' => get_post_type_object( 'page' )->labels->singular_name,
416 /* translators: %s: menu location */
417 'menuLocation' => _x( '(Currently set to: %s)', 'menu' ),
418 'menuNameLabel' => __( 'Menu Name' ),
419 'itemAdded' => __( 'Menu item added' ),
420 'itemDeleted' => __( 'Menu item deleted' ),
421 'menuAdded' => __( 'Menu created' ),
422 'menuDeleted' => __( 'Menu deleted' ),
423 'movedUp' => __( 'Menu item moved up' ),
424 'movedDown' => __( 'Menu item moved down' ),
425 'movedLeft' => __( 'Menu item moved out of submenu' ),
426 'movedRight' => __( 'Menu item is now a sub-item' ),
427 /* translators: ▸ is the unicode right-pointing triangle, and %s is the section title in the Customizer */
428 'customizingMenus' => sprintf( __( 'Customizing ▸ %s' ), esc_html( $this->manager->get_panel( 'nav_menus' )->title ) ),
429 /* translators: %s: title of menu item which is invalid */
430 'invalidTitleTpl' => __( '%s (Invalid)' ),
431 /* translators: %s: title of menu item in draft status */
432 'pendingTitleTpl' => __( '%s (Pending)' ),
433 'itemsFound' => __( 'Number of items found: %d' ),
434 'itemsFoundMore' => __( 'Additional items found: %d' ),
435 'itemsLoadingMore' => __( 'Loading more results... please wait.' ),
436 'reorderModeOn' => __( 'Reorder mode enabled' ),
437 'reorderModeOff' => __( 'Reorder mode closed' ),
438 'reorderLabelOn' => esc_attr__( 'Reorder menu items' ),
439 'reorderLabelOff' => esc_attr__( 'Close reorder mode' ),
441 'settingTransport' => 'postMessage',
442 'phpIntMax' => PHP_INT_MAX,
443 'defaultSettingValues' => array(
444 'nav_menu' => $temp_nav_menu_setting->default,
445 'nav_menu_item' => $temp_nav_menu_item_setting->default,
447 'locationSlugMappedToName' => get_registered_nav_menus(),
450 $data = sprintf( 'var _wpCustomizeNavMenusSettings = %s;', wp_json_encode( $settings ) );
451 wp_scripts()->add_data( 'customize-nav-menus', 'data', $data );
453 // This is copied from nav-menus.php, and it has an unfortunate object name of `menus`.
454 $nav_menus_l10n = array(
455 'oneThemeLocationNoMenus' => null,
456 'moveUp' => __( 'Move up one' ),
457 'moveDown' => __( 'Move down one' ),
458 'moveToTop' => __( 'Move to the top' ),
459 /* translators: %s: previous item name */
460 'moveUnder' => __( 'Move under %s' ),
461 /* translators: %s: previous item name */
462 'moveOutFrom' => __( 'Move out from under %s' ),
463 /* translators: %s: previous item name */
464 'under' => __( 'Under %s' ),
465 /* translators: %s: previous item name */
466 'outFrom' => __( 'Out from under %s' ),
467 /* translators: 1: item name, 2: item position, 3: total number of items */
468 'menuFocus' => __( '%1$s. Menu item %2$d of %3$d.' ),
469 /* translators: 1: item name, 2: item position, 3: parent item name */
470 'subMenuFocus' => __( '%1$s. Sub item number %2$d under %3$s.' ),
472 wp_localize_script( 'nav-menu', 'menus', $nav_menus_l10n );
476 * Filters a dynamic setting's constructor args.
478 * For a dynamic setting to be registered, this filter must be employed
479 * to override the default false value with an array of args to pass to
480 * the WP_Customize_Setting constructor.
485 * @param false|array $setting_args The arguments to the WP_Customize_Setting constructor.
486 * @param string $setting_id ID for dynamic setting, usually coming from `$_POST['customized']`.
487 * @return array|false
489 public function filter_dynamic_setting_args( $setting_args, $setting_id ) {
490 if ( preg_match( WP_Customize_Nav_Menu_Setting::ID_PATTERN, $setting_id ) ) {
491 $setting_args = array(
492 'type' => WP_Customize_Nav_Menu_Setting::TYPE,
493 'transport' => 'postMessage',
495 } elseif ( preg_match( WP_Customize_Nav_Menu_Item_Setting::ID_PATTERN, $setting_id ) ) {
496 $setting_args = array(
497 'type' => WP_Customize_Nav_Menu_Item_Setting::TYPE,
498 'transport' => 'postMessage',
501 return $setting_args;
505 * Allow non-statically created settings to be constructed with custom WP_Customize_Setting subclass.
510 * @param string $setting_class WP_Customize_Setting or a subclass.
511 * @param string $setting_id ID for dynamic setting, usually coming from `$_POST['customized']`.
512 * @param array $setting_args WP_Customize_Setting or a subclass.
515 public function filter_dynamic_setting_class( $setting_class, $setting_id, $setting_args ) {
516 unset( $setting_id );
518 if ( ! empty( $setting_args['type'] ) && WP_Customize_Nav_Menu_Setting::TYPE === $setting_args['type'] ) {
519 $setting_class = 'WP_Customize_Nav_Menu_Setting';
520 } elseif ( ! empty( $setting_args['type'] ) && WP_Customize_Nav_Menu_Item_Setting::TYPE === $setting_args['type'] ) {
521 $setting_class = 'WP_Customize_Nav_Menu_Item_Setting';
523 return $setting_class;
527 * Add the customizer settings and controls.
532 public function customize_register() {
535 * Preview settings for nav menus early so that the sections and controls will be added properly.
536 * See https://github.com/xwp/wp-customize-snapshots/blob/962586659688a5b1fd9ae93618b7ce2d4e7a421c/php/class-customize-snapshot-manager.php#L506-L543
538 $nav_menus_setting_ids = array();
539 foreach ( array_keys( $this->manager->unsanitized_post_values() ) as $setting_id ) {
540 if ( preg_match( '/^(nav_menu_locations|nav_menu|nav_menu_item)\[/', $setting_id ) ) {
541 $nav_menus_setting_ids[] = $setting_id;
544 $this->manager->add_dynamic_settings( $nav_menus_setting_ids );
545 foreach ( $nav_menus_setting_ids as $setting_id ) {
546 $setting = $this->manager->get_setting( $setting_id );
552 // Require JS-rendered control types.
553 $this->manager->register_panel_type( 'WP_Customize_Nav_Menus_Panel' );
554 $this->manager->register_control_type( 'WP_Customize_Nav_Menu_Control' );
555 $this->manager->register_control_type( 'WP_Customize_Nav_Menu_Name_Control' );
556 $this->manager->register_control_type( 'WP_Customize_Nav_Menu_Auto_Add_Control' );
557 $this->manager->register_control_type( 'WP_Customize_Nav_Menu_Item_Control' );
559 // Create a panel for Menus.
560 $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>';
561 if ( current_theme_supports( 'widgets' ) ) {
562 /* translators: URL to the widgets panel of the customizer */
563 $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>';
565 $description .= '<p>' . __( 'Menus can be displayed in locations defined by your theme.' ) . '</p>';
567 $this->manager->add_panel( new WP_Customize_Nav_Menus_Panel( $this->manager, 'nav_menus', array(
568 'title' => __( 'Menus' ),
569 'description' => $description,
571 // 'theme_supports' => 'menus|widgets', @todo allow multiple theme supports
573 $menus = wp_get_nav_menus();
576 $locations = get_registered_nav_menus();
577 $num_locations = count( array_keys( $locations ) );
578 if ( 1 == $num_locations ) {
579 $description = '<p>' . __( 'Your theme supports one menu. Select which menu you would like to use.' ) . '</p>';
581 /* translators: %s: number of menu locations */
582 $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>';
584 if ( current_theme_supports( 'widgets' ) ) {
585 /* translators: URL to the widgets panel of the customizer */
586 $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>';
589 $this->manager->add_section( 'menu_locations', array(
590 'title' => __( 'Menu Locations' ),
591 'panel' => 'nav_menus',
593 'description' => $description,
596 $choices = array( '0' => __( '— Select —' ) );
597 foreach ( $menus as $menu ) {
598 $choices[ $menu->term_id ] = wp_html_excerpt( $menu->name, 40, '…' );
601 foreach ( $locations as $location => $description ) {
602 $setting_id = "nav_menu_locations[{$location}]";
604 $setting = $this->manager->get_setting( $setting_id );
606 $setting->transport = 'postMessage';
607 remove_filter( "customize_sanitize_{$setting_id}", 'absint' );
608 add_filter( "customize_sanitize_{$setting_id}", array( $this, 'intval_base10' ) );
610 $this->manager->add_setting( $setting_id, array(
611 'sanitize_callback' => array( $this, 'intval_base10' ),
612 'theme_supports' => 'menus',
613 'type' => 'theme_mod',
614 'transport' => 'postMessage',
619 $this->manager->add_control( new WP_Customize_Nav_Menu_Location_Control( $this->manager, $setting_id, array(
620 'label' => $description,
621 'location_id' => $location,
622 'section' => 'menu_locations',
623 'choices' => $choices,
627 // Register each menu as a Customizer section, and add each menu item to each menu.
628 foreach ( $menus as $menu ) {
629 $menu_id = $menu->term_id;
631 // Create a section for each menu.
632 $section_id = 'nav_menu[' . $menu_id . ']';
633 $this->manager->add_section( new WP_Customize_Nav_Menu_Section( $this->manager, $section_id, array(
634 'title' => html_entity_decode( $menu->name, ENT_QUOTES, get_bloginfo( 'charset' ) ),
636 'panel' => 'nav_menus',
639 $nav_menu_setting_id = 'nav_menu[' . $menu_id . ']';
640 $this->manager->add_setting( new WP_Customize_Nav_Menu_Setting( $this->manager, $nav_menu_setting_id, array(
641 'transport' => 'postMessage',
644 // Add the menu contents.
645 $menu_items = (array) wp_get_nav_menu_items( $menu_id );
647 foreach ( array_values( $menu_items ) as $i => $item ) {
649 // Create a setting for each menu item (which doesn't actually manage data, currently).
650 $menu_item_setting_id = 'nav_menu_item[' . $item->ID . ']';
652 $value = (array) $item;
653 if ( empty( $value['post_title'] ) ) {
654 $value['title'] = '';
657 $value['nav_menu_term_id'] = $menu_id;
658 $this->manager->add_setting( new WP_Customize_Nav_Menu_Item_Setting( $this->manager, $menu_item_setting_id, array(
660 'transport' => 'postMessage',
663 // Create a control for each menu item.
664 $this->manager->add_control( new WP_Customize_Nav_Menu_Item_Control( $this->manager, $menu_item_setting_id, array(
665 'label' => $item->title,
666 'section' => $section_id,
667 'priority' => 10 + $i,
671 // Note: other controls inside of this section get added dynamically in JS via the MenuSection.ready() function.
674 // Add the add-new-menu section and controls.
675 $this->manager->add_section( new WP_Customize_New_Menu_Section( $this->manager, 'add_menu', array(
676 'title' => __( 'Add a Menu' ),
677 'panel' => 'nav_menus',
681 $this->manager->add_control( 'new_menu_name', array(
683 'section' => 'add_menu',
685 'settings' => array(),
686 'input_attrs' => array(
687 'class' => 'menu-name-field',
688 'placeholder' => __( 'New menu name' ),
692 $this->manager->add_control( new WP_Customize_New_Menu_Control( $this->manager, 'create_new_menu', array(
693 'section' => 'add_menu',
694 'settings' => array(),
697 $this->manager->add_setting( new WP_Customize_Filter_Setting( $this->manager, 'nav_menus_created_posts', array(
698 'transport' => 'postMessage',
699 'type' => 'option', // To prevent theme prefix in changeset.
700 'default' => array(),
701 'sanitize_callback' => array( $this, 'sanitize_nav_menus_created_posts' ),
706 * Get the base10 intval.
708 * This is used as a setting's sanitize_callback; we can't use just plain
709 * intval because the second argument is not what intval() expects.
714 * @param mixed $value Number to convert.
715 * @return int Integer.
717 public function intval_base10( $value ) {
718 return intval( $value, 10 );
722 * Return an array of all the available item types.
725 * @since 4.7.0 Each array item now includes a `$type_label` in in addition to `$title`, `$type`, and `$object`.
728 * @return array The available menu item types.
730 public function available_item_types() {
731 $item_types = array();
733 $post_types = get_post_types( array( 'show_in_nav_menus' => true ), 'objects' );
735 foreach ( $post_types as $slug => $post_type ) {
736 $item_types[] = array(
737 'title' => $post_type->labels->name,
738 'type_label' => $post_type->labels->singular_name,
739 'type' => 'post_type',
740 'object' => $post_type->name,
745 $taxonomies = get_taxonomies( array( 'show_in_nav_menus' => true ), 'objects' );
747 foreach ( $taxonomies as $slug => $taxonomy ) {
748 if ( 'post_format' === $taxonomy && ! current_theme_supports( 'post-formats' ) ) {
751 $item_types[] = array(
752 'title' => $taxonomy->labels->name,
753 'type_label' => $taxonomy->labels->singular_name,
754 'type' => 'taxonomy',
755 'object' => $taxonomy->name,
761 * Filters the available menu item types.
764 * @since 4.7.0 Each array item now includes a `$type_label` in in addition to `$title`, `$type`, and `$object`.
766 * @param array $item_types Custom menu item types.
768 $item_types = apply_filters( 'customize_nav_menu_available_item_types', $item_types );
774 * Add a new `auto-draft` post.
779 * @param array $postarr {
780 * Post array. Note that post_status is overridden to be `auto-draft`.
782 * @var string $post_title Post title. Required.
783 * @var string $post_type Post type. Required.
784 * @var string $post_name Post name.
785 * @var string $post_content Post content.
787 * @return WP_Post|WP_Error Inserted auto-draft post object or error.
789 public function insert_auto_draft_post( $postarr ) {
790 if ( ! isset( $postarr['post_type'] ) || ! post_type_exists( $postarr['post_type'] ) ) {
791 return new WP_Error( 'unknown_post_type', __( 'Unknown post type' ) );
793 if ( empty( $postarr['post_title'] ) ) {
794 return new WP_Error( 'empty_title', __( 'Empty title' ) );
796 if ( ! empty( $postarr['post_status'] ) ) {
797 return new WP_Error( 'status_forbidden', __( 'Status is forbidden' ) );
800 $postarr['post_status'] = 'auto-draft';
802 // Auto-drafts are allowed to have empty post_names, so it has to be explicitly set.
803 if ( empty( $postarr['post_name'] ) ) {
804 $postarr['post_name'] = sanitize_title( $postarr['post_title'] );
806 if ( ! isset( $postarr['meta_input'] ) ) {
807 $postarr['meta_input'] = array();
809 $postarr['meta_input']['_customize_draft_post_name'] = $postarr['post_name'];
810 unset( $postarr['post_name'] );
812 add_filter( 'wp_insert_post_empty_content', '__return_false', 1000 );
813 $r = wp_insert_post( wp_slash( $postarr ), true );
814 remove_filter( 'wp_insert_post_empty_content', '__return_false', 1000 );
816 if ( is_wp_error( $r ) ) {
819 return get_post( $r );
824 * Ajax handler for adding a new auto-draft post.
829 public function ajax_insert_auto_draft_post() {
830 if ( ! check_ajax_referer( 'customize-menus', 'customize-menus-nonce', false ) ) {
831 wp_send_json_error( 'bad_nonce', 400 );
834 if ( ! current_user_can( 'customize' ) ) {
835 wp_send_json_error( 'customize_not_allowed', 403 );
838 if ( empty( $_POST['params'] ) || ! is_array( $_POST['params'] ) ) {
839 wp_send_json_error( 'missing_params', 400 );
842 $params = wp_unslash( $_POST['params'] );
843 $illegal_params = array_diff( array_keys( $params ), array( 'post_type', 'post_title' ) );
844 if ( ! empty( $illegal_params ) ) {
845 wp_send_json_error( 'illegal_params', 400 );
848 $params = array_merge(
856 if ( empty( $params['post_type'] ) || ! post_type_exists( $params['post_type'] ) ) {
857 status_header( 400 );
858 wp_send_json_error( 'missing_post_type_param' );
861 $post_type_object = get_post_type_object( $params['post_type'] );
862 if ( ! current_user_can( $post_type_object->cap->create_posts ) || ! current_user_can( $post_type_object->cap->publish_posts ) ) {
863 status_header( 403 );
864 wp_send_json_error( 'insufficient_post_permissions' );
867 $params['post_title'] = trim( $params['post_title'] );
868 if ( '' === $params['post_title'] ) {
869 status_header( 400 );
870 wp_send_json_error( 'missing_post_title' );
873 $r = $this->insert_auto_draft_post( $params );
874 if ( is_wp_error( $r ) ) {
876 if ( ! empty( $post_type_object->labels->singular_name ) ) {
877 $singular_name = $post_type_object->labels->singular_name;
879 $singular_name = __( 'Post' );
883 /* translators: %1$s is the post type name and %2$s is the error message. */
884 'message' => sprintf( __( '%1$s could not be created: %2$s' ), $singular_name, $error->get_error_message() ),
886 wp_send_json_error( $data );
890 'post_id' => $post->ID,
891 'url' => get_permalink( $post->ID ),
893 wp_send_json_success( $data );
898 * Print the JavaScript templates used to render Menu Customizer components.
900 * Templates are imported into the JS use wp.template.
905 public function print_templates() {
907 <script type="text/html" id="tmpl-available-menu-item">
908 <li id="menu-item-tpl-{{ data.id }}" class="menu-item-tpl" data-menu-item-id="{{ data.id }}">
909 <div class="menu-item-bar">
910 <div class="menu-item-handle">
911 <span class="item-type" aria-hidden="true">{{ data.type_label }}</span>
912 <span class="item-title" aria-hidden="true">
913 <span class="menu-item-title<# if ( ! data.title ) { #> no-title<# } #>">{{ data.title || wp.customize.Menus.data.l10n.untitled }}</span>
915 <button type="button" class="button-link item-add">
916 <span class="screen-reader-text"><?php
917 /* translators: 1: Title of a menu item, 2: Type of a menu item */
918 printf( __( 'Add to menu: %1$s (%2$s)' ), '{{ data.title || wp.customize.Menus.data.l10n.untitled }}', '{{ data.type_label }}' );
926 <script type="text/html" id="tmpl-menu-item-reorder-nav">
927 <div class="menu-item-reorder-nav">
930 '<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>',
933 __( 'Move one level up' ),
934 __( 'Move one level down' )
943 * Print the html template used to render the add-menu-item frame.
948 public function available_items_template() {
950 <div id="available-menu-items" class="accordion-container">
951 <div class="customize-section-title">
952 <button type="button" class="customize-section-back" tabindex="-1">
953 <span class="screen-reader-text"><?php _e( 'Back' ); ?></span>
956 <span class="customize-action">
958 /* translators: ▸ is the unicode right-pointing triangle, and %s is the section title in the Customizer */
959 printf( __( 'Customizing ▸ %s' ), esc_html( $this->manager->get_panel( 'nav_menus' )->title ) );
962 <?php _e( 'Add Menu Items' ); ?>
965 <div id="available-menu-items-search" class="accordion-section cannot-expand">
966 <div class="accordion-section-title">
967 <label class="screen-reader-text" for="menu-items-search"><?php _e( 'Search Menu Items' ); ?></label>
968 <input type="text" id="menu-items-search" placeholder="<?php esc_attr_e( 'Search menu items…' ) ?>" aria-describedby="menu-items-search-desc" />
969 <p class="screen-reader-text" id="menu-items-search-desc"><?php _e( 'The search results will be updated as you type.' ); ?></p>
970 <span class="spinner"></span>
972 <div class="search-icon" aria-hidden="true"></div>
973 <button type="button" class="clear-results"><span class="screen-reader-text"><?php _e( 'Clear Results' ); ?></span></button>
974 <ul class="accordion-section-content available-menu-items-list" data-type="search"></ul>
978 // Ensure the page post type comes first in the list.
979 $item_types = $this->available_item_types();
980 $page_item_type = null;
981 foreach ( $item_types as $i => $item_type ) {
982 if ( isset( $item_type['object'] ) && 'page' === $item_type['object'] ) {
983 $page_item_type = $item_type;
984 unset( $item_types[ $i ] );
988 $this->print_custom_links_available_menu_item();
989 if ( $page_item_type ) {
990 $this->print_post_type_container( $page_item_type );
992 // Containers for per-post-type item browsing; items are added with JS.
993 foreach ( $item_types as $item_type ) {
994 $this->print_post_type_container( $item_type );
997 </div><!-- #available-menu-items -->
1002 * Print the markup for new menu items.
1004 * To be used in the template #available-menu-items.
1009 * @param array $available_item_type Menu item data to output, including title, type, and label.
1012 protected function print_post_type_container( $available_item_type ) {
1013 $id = sprintf( 'available-menu-items-%s-%s', $available_item_type['type'], $available_item_type['object'] );
1015 <div id="<?php echo esc_attr( $id ); ?>" class="accordion-section">
1016 <h4 class="accordion-section-title" role="presentation">
1017 <?php echo esc_html( $available_item_type['title'] ); ?>
1018 <span class="spinner"></span>
1019 <span class="no-items"><?php _e( 'No items' ); ?></span>
1020 <button type="button" class="button-link" aria-expanded="false">
1021 <span class="screen-reader-text"><?php
1022 /* translators: %s: Title of a section with menu items */
1023 printf( __( 'Toggle section: %s' ), esc_html( $available_item_type['title'] ) ); ?></span>
1024 <span class="toggle-indicator" aria-hidden="true"></span>
1027 <div class="accordion-section-content">
1028 <?php if ( 'post_type' === $available_item_type['type'] ) : ?>
1029 <?php $post_type_obj = get_post_type_object( $available_item_type['object'] ); ?>
1030 <?php if ( current_user_can( $post_type_obj->cap->create_posts ) && current_user_can( $post_type_obj->cap->publish_posts ) ) : ?>
1031 <div class="new-content-item">
1032 <input type="text" class="create-item-input" placeholder="<?php echo esc_attr( $post_type_obj->labels->add_new_item ); ?>">
1033 <button type="button" class="button add-content"><?php _e( 'Add' ); ?></button>
1037 <ul class="available-menu-items-list" data-type="<?php echo esc_attr( $available_item_type['type'] ); ?>" data-object="<?php echo esc_attr( $available_item_type['object'] ); ?>" data-type_label="<?php echo esc_attr( isset( $available_item_type['type_label'] ) ? $available_item_type['type_label'] : $available_item_type['type'] ); ?>"></ul>
1044 * Print the markup for available menu item custom links.
1051 protected function print_custom_links_available_menu_item() {
1053 <div id="new-custom-menu-item" class="accordion-section">
1054 <h4 class="accordion-section-title" role="presentation">
1055 <?php _e( 'Custom Links' ); ?>
1056 <button type="button" class="button-link" aria-expanded="false">
1057 <span class="screen-reader-text"><?php _e( 'Toggle section: Custom Links' ); ?></span>
1058 <span class="toggle-indicator" aria-hidden="true"></span>
1061 <div class="accordion-section-content customlinkdiv">
1062 <input type="hidden" value="custom" id="custom-menu-item-type" name="menu-item[-1][menu-item-type]" />
1063 <p id="menu-item-url-wrap" class="wp-clearfix">
1064 <label class="howto" for="custom-menu-item-url"><?php _e( 'URL' ); ?></label>
1065 <input id="custom-menu-item-url" name="menu-item[-1][menu-item-url]" type="text" class="code menu-item-textbox" value="http://">
1067 <p id="menu-item-name-wrap" class="wp-clearfix">
1068 <label class="howto" for="custom-menu-item-name"><?php _e( 'Link Text' ); ?></label>
1069 <input id="custom-menu-item-name" name="menu-item[-1][menu-item-title]" type="text" class="regular-text menu-item-textbox">
1071 <p class="button-controls">
1072 <span class="add-to-menu">
1073 <input type="submit" class="button submit-add-to-menu right" value="<?php esc_attr_e( 'Add to Menu' ); ?>" name="add-custom-menu-item" id="custom-menu-item-submit">
1074 <span class="spinner"></span>
1083 // Start functionality specific to partial-refresh of menu changes in Customizer preview.
1087 * Nav menu args used for each instance, keyed by the args HMAC.
1093 public $preview_nav_menu_instance_args = array();
1096 * Filters arguments for dynamic nav_menu selective refresh partials.
1101 * @param array|false $partial_args Partial args.
1102 * @param string $partial_id Partial ID.
1103 * @return array Partial args.
1105 public function customize_dynamic_partial_args( $partial_args, $partial_id ) {
1107 if ( preg_match( '/^nav_menu_instance\[[0-9a-f]{32}\]$/', $partial_id ) ) {
1108 if ( false === $partial_args ) {
1109 $partial_args = array();
1111 $partial_args = array_merge(
1114 'type' => 'nav_menu_instance',
1115 'render_callback' => array( $this, 'render_nav_menu_partial' ),
1116 'container_inclusive' => true,
1117 'settings' => array(), // Empty because the nav menu instance may relate to a menu or a location.
1118 'capability' => 'edit_theme_options',
1123 return $partial_args;
1127 * Add hooks for the Customizer preview.
1132 public function customize_preview_init() {
1133 add_action( 'wp_enqueue_scripts', array( $this, 'customize_preview_enqueue_deps' ) );
1134 add_filter( 'wp_nav_menu_args', array( $this, 'filter_wp_nav_menu_args' ), 1000 );
1135 add_filter( 'wp_nav_menu', array( $this, 'filter_wp_nav_menu' ), 10, 2 );
1136 add_filter( 'wp_footer', array( $this, 'export_preview_data' ), 1 );
1137 add_filter( 'customize_render_partials_response', array( $this, 'export_partial_rendered_nav_menu_instances' ) );
1141 * Make the auto-draft status protected so that it can be queried.
1146 public function make_auto_draft_status_previewable() {
1147 global $wp_post_statuses;
1148 $wp_post_statuses['auto-draft']->protected = true;
1152 * Sanitize post IDs for auto-draft posts created for nav menu items to be published.
1157 * @param array $value Post IDs.
1158 * @returns array Post IDs.
1160 public function sanitize_nav_menus_created_posts( $value ) {
1161 $post_ids = array();
1162 foreach ( wp_parse_id_list( $value ) as $post_id ) {
1163 if ( empty( $post_id ) ) {
1166 $post = get_post( $post_id );
1167 if ( 'auto-draft' !== $post->post_status ) {
1170 $post_type_obj = get_post_type_object( $post->post_type );
1171 if ( ! $post_type_obj ) {
1174 if ( ! current_user_can( $post_type_obj->cap->publish_posts ) || ! current_user_can( $post_type_obj->cap->edit_post, $post_id ) ) {
1177 $post_ids[] = $post->ID;
1183 * Publish the auto-draft posts that were created for nav menu items.
1185 * The post IDs will have been sanitized by already by
1186 * `WP_Customize_Nav_Menu_Items::sanitize_nav_menus_created_posts()` to
1187 * remove any post IDs for which the user cannot publish or for which the
1188 * post is not an auto-draft.
1193 * @param WP_Customize_Setting $setting Customizer setting object.
1195 public function save_nav_menus_created_posts( $setting ) {
1196 $post_ids = $setting->post_value();
1197 if ( ! empty( $post_ids ) ) {
1198 foreach ( $post_ids as $post_id ) {
1199 $target_status = 'attachment' === get_post_type( $post_id ) ? 'inherit' : 'publish';
1202 'post_status' => $target_status,
1204 $post_name = get_post_meta( $post_id, '_customize_draft_post_name', true );
1206 $args['post_name'] = $post_name;
1209 // Note that wp_publish_post() cannot be used because unique slugs need to be assigned.
1210 wp_update_post( wp_slash( $args ) );
1212 delete_post_meta( $post_id, '_customize_draft_post_name' );
1218 * Keep track of the arguments that are being passed to wp_nav_menu().
1222 * @see wp_nav_menu()
1223 * @see WP_Customize_Widgets_Partial_Refresh::filter_dynamic_sidebar_params()
1225 * @param array $args An array containing wp_nav_menu() arguments.
1226 * @return array Arguments.
1228 public function filter_wp_nav_menu_args( $args ) {
1230 * The following conditions determine whether or not this instance of
1231 * wp_nav_menu() can use selective refreshed. A wp_nav_menu() can be
1232 * selective refreshed if...
1234 $can_partial_refresh = (
1235 // ...if wp_nav_menu() is directly echoing out the menu (and thus isn't manipulating the string after generated),
1236 ! empty( $args['echo'] )
1238 // ...and if the fallback_cb can be serialized to JSON, since it will be included in the placement context data,
1239 ( empty( $args['fallback_cb'] ) || is_string( $args['fallback_cb'] ) )
1241 // ...and if the walker can also be serialized to JSON, since it will be included in the placement context data as well,
1242 ( empty( $args['walker'] ) || is_string( $args['walker'] ) )
1243 // ...and if it has a theme location assigned or an assigned menu to display,
1245 ! empty( $args['theme_location'] )
1247 ( ! empty( $args['menu'] ) && ( is_numeric( $args['menu'] ) || is_object( $args['menu'] ) ) )
1250 // ...and if the nav menu would be rendered with a wrapper container element (upon which to attach data-* attributes).
1252 ! empty( $args['container'] )
1254 ( isset( $args['items_wrap'] ) && '<' === substr( $args['items_wrap'], 0, 1 ) )
1257 $args['can_partial_refresh'] = $can_partial_refresh;
1259 $exported_args = $args;
1261 // Empty out args which may not be JSON-serializable.
1262 if ( ! $can_partial_refresh ) {
1263 $exported_args['fallback_cb'] = '';
1264 $exported_args['walker'] = '';
1268 * Replace object menu arg with a term_id menu arg, as this exports better
1269 * to JS and is easier to compare hashes.
1271 if ( ! empty( $exported_args['menu'] ) && is_object( $exported_args['menu'] ) ) {
1272 $exported_args['menu'] = $exported_args['menu']->term_id;
1275 ksort( $exported_args );
1276 $exported_args['args_hmac'] = $this->hash_nav_menu_args( $exported_args );
1278 $args['customize_preview_nav_menus_args'] = $exported_args;
1279 $this->preview_nav_menu_instance_args[ $exported_args['args_hmac'] ] = $exported_args;
1284 * Prepares wp_nav_menu() calls for partial refresh.
1286 * Injects attributes into container element.
1291 * @see wp_nav_menu()
1293 * @param string $nav_menu_content The HTML content for the navigation menu.
1294 * @param object $args An object containing wp_nav_menu() arguments.
1297 public function filter_wp_nav_menu( $nav_menu_content, $args ) {
1298 if ( isset( $args->customize_preview_nav_menus_args['can_partial_refresh'] ) && $args->customize_preview_nav_menus_args['can_partial_refresh'] ) {
1299 $attributes = sprintf( ' data-customize-partial-id="%s"', esc_attr( 'nav_menu_instance[' . $args->customize_preview_nav_menus_args['args_hmac'] . ']' ) );
1300 $attributes .= ' data-customize-partial-type="nav_menu_instance"';
1301 $attributes .= sprintf( ' data-customize-partial-placement-context="%s"', esc_attr( wp_json_encode( $args->customize_preview_nav_menus_args ) ) );
1302 $nav_menu_content = preg_replace( '#^(<\w+)#', '$1 ' . $attributes, $nav_menu_content, 1 );
1304 return $nav_menu_content;
1308 * Hashes (hmac) the nav menu arguments to ensure they are not tampered with when
1309 * submitted in the Ajax request.
1311 * Note that the array is expected to be pre-sorted.
1316 * @param array $args The arguments to hash.
1317 * @return string Hashed nav menu arguments.
1319 public function hash_nav_menu_args( $args ) {
1320 return wp_hash( serialize( $args ) );
1324 * Enqueue scripts for the Customizer preview.
1329 public function customize_preview_enqueue_deps() {
1330 wp_enqueue_script( 'customize-preview-nav-menus' ); // Note that we have overridden this.
1331 wp_enqueue_style( 'customize-preview' );
1335 * Exports data from PHP to JS.
1340 public function export_preview_data() {
1342 // Why not wp_localize_script? Because we're not localizing, and it forces values into strings.
1344 'navMenuInstanceArgs' => $this->preview_nav_menu_instance_args,
1346 printf( '<script>var _wpCustomizePreviewNavMenusExports = %s;</script>', wp_json_encode( $exports ) );
1350 * Export any wp_nav_menu() calls during the rendering of any partials.
1355 * @param array $response Response.
1356 * @return array Response.
1358 public function export_partial_rendered_nav_menu_instances( $response ) {
1359 $response['nav_menu_instance_args'] = $this->preview_nav_menu_instance_args;
1364 * Render a specific menu via wp_nav_menu() using the supplied arguments.
1369 * @see wp_nav_menu()
1371 * @param WP_Customize_Partial $partial Partial.
1372 * @param array $nav_menu_args Nav menu args supplied as container context.
1373 * @return string|false
1375 public function render_nav_menu_partial( $partial, $nav_menu_args ) {
1378 if ( ! isset( $nav_menu_args['args_hmac'] ) ) {
1379 // Error: missing_args_hmac.
1383 $nav_menu_args_hmac = $nav_menu_args['args_hmac'];
1384 unset( $nav_menu_args['args_hmac'] );
1386 ksort( $nav_menu_args );
1387 if ( ! hash_equals( $this->hash_nav_menu_args( $nav_menu_args ), $nav_menu_args_hmac ) ) {
1388 // Error: args_hmac_mismatch.
1393 wp_nav_menu( $nav_menu_args );
1394 $content = ob_get_clean();