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() {
534 // Preview settings for nav menus early so that the sections and controls will be added properly.
535 $nav_menus_setting_ids = array();
536 foreach ( array_keys( $this->manager->unsanitized_post_values() ) as $setting_id ) {
537 if ( preg_match( '/^(nav_menu_locations|nav_menu|nav_menu_item)\[/', $setting_id ) ) {
538 $nav_menus_setting_ids[] = $setting_id;
541 $this->manager->add_dynamic_settings( $nav_menus_setting_ids );
542 if ( ! $this->manager->doing_ajax( 'customize_save' ) ) {
543 foreach ( $nav_menus_setting_ids as $setting_id ) {
544 $setting = $this->manager->get_setting( $setting_id );
551 // Require JS-rendered control types.
552 $this->manager->register_panel_type( 'WP_Customize_Nav_Menus_Panel' );
553 $this->manager->register_control_type( 'WP_Customize_Nav_Menu_Control' );
554 $this->manager->register_control_type( 'WP_Customize_Nav_Menu_Name_Control' );
555 $this->manager->register_control_type( 'WP_Customize_Nav_Menu_Auto_Add_Control' );
556 $this->manager->register_control_type( 'WP_Customize_Nav_Menu_Item_Control' );
558 // Create a panel for Menus.
559 $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>';
560 if ( current_theme_supports( 'widgets' ) ) {
561 /* translators: URL to the widgets panel of the customizer */
562 $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>';
564 $description .= '<p>' . __( 'Menus can be displayed in locations defined by your theme.' ) . '</p>';
566 $this->manager->add_panel( new WP_Customize_Nav_Menus_Panel( $this->manager, 'nav_menus', array(
567 'title' => __( 'Menus' ),
568 'description' => $description,
570 // 'theme_supports' => 'menus|widgets', @todo allow multiple theme supports
572 $menus = wp_get_nav_menus();
575 $locations = get_registered_nav_menus();
576 $num_locations = count( array_keys( $locations ) );
577 if ( 1 == $num_locations ) {
578 $description = '<p>' . __( 'Your theme supports one menu. Select which menu you would like to use.' ) . '</p>';
580 /* translators: %s: number of menu locations */
581 $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>';
583 if ( current_theme_supports( 'widgets' ) ) {
584 /* translators: URL to the widgets panel of the customizer */
585 $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>';
588 $this->manager->add_section( 'menu_locations', array(
589 'title' => __( 'Menu Locations' ),
590 'panel' => 'nav_menus',
592 'description' => $description,
595 $choices = array( '0' => __( '— Select —' ) );
596 foreach ( $menus as $menu ) {
597 $choices[ $menu->term_id ] = wp_html_excerpt( $menu->name, 40, '…' );
600 foreach ( $locations as $location => $description ) {
601 $setting_id = "nav_menu_locations[{$location}]";
603 $setting = $this->manager->get_setting( $setting_id );
605 $setting->transport = 'postMessage';
606 remove_filter( "customize_sanitize_{$setting_id}", 'absint' );
607 add_filter( "customize_sanitize_{$setting_id}", array( $this, 'intval_base10' ) );
609 $this->manager->add_setting( $setting_id, array(
610 'sanitize_callback' => array( $this, 'intval_base10' ),
611 'theme_supports' => 'menus',
612 'type' => 'theme_mod',
613 'transport' => 'postMessage',
618 $this->manager->add_control( new WP_Customize_Nav_Menu_Location_Control( $this->manager, $setting_id, array(
619 'label' => $description,
620 'location_id' => $location,
621 'section' => 'menu_locations',
622 'choices' => $choices,
626 // Register each menu as a Customizer section, and add each menu item to each menu.
627 foreach ( $menus as $menu ) {
628 $menu_id = $menu->term_id;
630 // Create a section for each menu.
631 $section_id = 'nav_menu[' . $menu_id . ']';
632 $this->manager->add_section( new WP_Customize_Nav_Menu_Section( $this->manager, $section_id, array(
633 'title' => html_entity_decode( $menu->name, ENT_QUOTES, get_bloginfo( 'charset' ) ),
635 'panel' => 'nav_menus',
638 $nav_menu_setting_id = 'nav_menu[' . $menu_id . ']';
639 $this->manager->add_setting( new WP_Customize_Nav_Menu_Setting( $this->manager, $nav_menu_setting_id, array(
640 'transport' => 'postMessage',
643 // Add the menu contents.
644 $menu_items = (array) wp_get_nav_menu_items( $menu_id );
646 foreach ( array_values( $menu_items ) as $i => $item ) {
648 // Create a setting for each menu item (which doesn't actually manage data, currently).
649 $menu_item_setting_id = 'nav_menu_item[' . $item->ID . ']';
651 $value = (array) $item;
652 if ( empty( $value['post_title'] ) ) {
653 $value['title'] = '';
656 $value['nav_menu_term_id'] = $menu_id;
657 $this->manager->add_setting( new WP_Customize_Nav_Menu_Item_Setting( $this->manager, $menu_item_setting_id, array(
659 'transport' => 'postMessage',
662 // Create a control for each menu item.
663 $this->manager->add_control( new WP_Customize_Nav_Menu_Item_Control( $this->manager, $menu_item_setting_id, array(
664 'label' => $item->title,
665 'section' => $section_id,
666 'priority' => 10 + $i,
670 // Note: other controls inside of this section get added dynamically in JS via the MenuSection.ready() function.
673 // Add the add-new-menu section and controls.
674 $this->manager->add_section( new WP_Customize_New_Menu_Section( $this->manager, 'add_menu', array(
675 'title' => __( 'Add a Menu' ),
676 'panel' => 'nav_menus',
680 $this->manager->add_control( 'new_menu_name', array(
682 'section' => 'add_menu',
684 'settings' => array(),
685 'input_attrs' => array(
686 'class' => 'menu-name-field',
687 'placeholder' => __( 'New menu name' ),
691 $this->manager->add_control( new WP_Customize_New_Menu_Control( $this->manager, 'create_new_menu', array(
692 'section' => 'add_menu',
693 'settings' => array(),
696 $this->manager->add_setting( new WP_Customize_Filter_Setting( $this->manager, 'nav_menus_created_posts', array(
697 'transport' => 'postMessage',
698 'type' => 'option', // To prevent theme prefix in changeset.
699 'default' => array(),
700 'sanitize_callback' => array( $this, 'sanitize_nav_menus_created_posts' ),
705 * Get the base10 intval.
707 * This is used as a setting's sanitize_callback; we can't use just plain
708 * intval because the second argument is not what intval() expects.
713 * @param mixed $value Number to convert.
714 * @return int Integer.
716 public function intval_base10( $value ) {
717 return intval( $value, 10 );
721 * Return an array of all the available item types.
724 * @since 4.7.0 Each array item now includes a `$type_label` in in addition to `$title`, `$type`, and `$object`.
727 * @return array The available menu item types.
729 public function available_item_types() {
730 $item_types = array();
732 $post_types = get_post_types( array( 'show_in_nav_menus' => true ), 'objects' );
734 foreach ( $post_types as $slug => $post_type ) {
735 $item_types[] = array(
736 'title' => $post_type->labels->name,
737 'type_label' => $post_type->labels->singular_name,
738 'type' => 'post_type',
739 'object' => $post_type->name,
744 $taxonomies = get_taxonomies( array( 'show_in_nav_menus' => true ), 'objects' );
746 foreach ( $taxonomies as $slug => $taxonomy ) {
747 if ( 'post_format' === $taxonomy && ! current_theme_supports( 'post-formats' ) ) {
750 $item_types[] = array(
751 'title' => $taxonomy->labels->name,
752 'type_label' => $taxonomy->labels->singular_name,
753 'type' => 'taxonomy',
754 'object' => $taxonomy->name,
760 * Filters the available menu item types.
763 * @since 4.7.0 Each array item now includes a `$type_label` in in addition to `$title`, `$type`, and `$object`.
765 * @param array $item_types Custom menu item types.
767 $item_types = apply_filters( 'customize_nav_menu_available_item_types', $item_types );
773 * Add a new `auto-draft` post.
778 * @param array $postarr {
779 * Post array. Note that post_status is overridden to be `auto-draft`.
781 * @var string $post_title Post title. Required.
782 * @var string $post_type Post type. Required.
783 * @var string $post_name Post name.
784 * @var string $post_content Post content.
786 * @return WP_Post|WP_Error Inserted auto-draft post object or error.
788 public function insert_auto_draft_post( $postarr ) {
789 if ( ! isset( $postarr['post_type'] ) || ! post_type_exists( $postarr['post_type'] ) ) {
790 return new WP_Error( 'unknown_post_type', __( 'Unknown post type' ) );
792 if ( empty( $postarr['post_title'] ) ) {
793 return new WP_Error( 'empty_title', __( 'Empty title' ) );
795 if ( ! empty( $postarr['post_status'] ) ) {
796 return new WP_Error( 'status_forbidden', __( 'Status is forbidden' ) );
799 $postarr['post_status'] = 'auto-draft';
801 // Auto-drafts are allowed to have empty post_names, so it has to be explicitly set.
802 if ( empty( $postarr['post_name'] ) ) {
803 $postarr['post_name'] = sanitize_title( $postarr['post_title'] );
805 if ( ! isset( $postarr['meta_input'] ) ) {
806 $postarr['meta_input'] = array();
808 $postarr['meta_input']['_customize_draft_post_name'] = $postarr['post_name'];
809 unset( $postarr['post_name'] );
811 add_filter( 'wp_insert_post_empty_content', '__return_false', 1000 );
812 $r = wp_insert_post( wp_slash( $postarr ), true );
813 remove_filter( 'wp_insert_post_empty_content', '__return_false', 1000 );
815 if ( is_wp_error( $r ) ) {
818 return get_post( $r );
823 * Ajax handler for adding a new auto-draft post.
828 public function ajax_insert_auto_draft_post() {
829 if ( ! check_ajax_referer( 'customize-menus', 'customize-menus-nonce', false ) ) {
830 wp_send_json_error( 'bad_nonce', 400 );
833 if ( ! current_user_can( 'customize' ) ) {
834 wp_send_json_error( 'customize_not_allowed', 403 );
837 if ( empty( $_POST['params'] ) || ! is_array( $_POST['params'] ) ) {
838 wp_send_json_error( 'missing_params', 400 );
841 $params = wp_unslash( $_POST['params'] );
842 $illegal_params = array_diff( array_keys( $params ), array( 'post_type', 'post_title' ) );
843 if ( ! empty( $illegal_params ) ) {
844 wp_send_json_error( 'illegal_params', 400 );
847 $params = array_merge(
855 if ( empty( $params['post_type'] ) || ! post_type_exists( $params['post_type'] ) ) {
856 status_header( 400 );
857 wp_send_json_error( 'missing_post_type_param' );
860 $post_type_object = get_post_type_object( $params['post_type'] );
861 if ( ! current_user_can( $post_type_object->cap->create_posts ) || ! current_user_can( $post_type_object->cap->publish_posts ) ) {
862 status_header( 403 );
863 wp_send_json_error( 'insufficient_post_permissions' );
866 $params['post_title'] = trim( $params['post_title'] );
867 if ( '' === $params['post_title'] ) {
868 status_header( 400 );
869 wp_send_json_error( 'missing_post_title' );
872 $r = $this->insert_auto_draft_post( $params );
873 if ( is_wp_error( $r ) ) {
875 if ( ! empty( $post_type_object->labels->singular_name ) ) {
876 $singular_name = $post_type_object->labels->singular_name;
878 $singular_name = __( 'Post' );
882 /* translators: %1$s is the post type name and %2$s is the error message. */
883 'message' => sprintf( __( '%1$s could not be created: %2$s' ), $singular_name, $error->get_error_message() ),
885 wp_send_json_error( $data );
889 'post_id' => $post->ID,
890 'url' => get_permalink( $post->ID ),
892 wp_send_json_success( $data );
897 * Print the JavaScript templates used to render Menu Customizer components.
899 * Templates are imported into the JS use wp.template.
904 public function print_templates() {
906 <script type="text/html" id="tmpl-available-menu-item">
907 <li id="menu-item-tpl-{{ data.id }}" class="menu-item-tpl" data-menu-item-id="{{ data.id }}">
908 <div class="menu-item-bar">
909 <div class="menu-item-handle">
910 <span class="item-type" aria-hidden="true">{{ data.type_label }}</span>
911 <span class="item-title" aria-hidden="true">
912 <span class="menu-item-title<# if ( ! data.title ) { #> no-title<# } #>">{{ data.title || wp.customize.Menus.data.l10n.untitled }}</span>
914 <button type="button" class="button-link item-add">
915 <span class="screen-reader-text"><?php
916 /* translators: 1: Title of a menu item, 2: Type of a menu item */
917 printf( __( 'Add to menu: %1$s (%2$s)' ), '{{ data.title || wp.customize.Menus.data.l10n.untitled }}', '{{ data.type_label }}' );
925 <script type="text/html" id="tmpl-menu-item-reorder-nav">
926 <div class="menu-item-reorder-nav">
929 '<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>',
932 __( 'Move one level up' ),
933 __( 'Move one level down' )
942 * Print the html template used to render the add-menu-item frame.
947 public function available_items_template() {
949 <div id="available-menu-items" class="accordion-container">
950 <div class="customize-section-title">
951 <button type="button" class="customize-section-back" tabindex="-1">
952 <span class="screen-reader-text"><?php _e( 'Back' ); ?></span>
955 <span class="customize-action">
957 /* translators: ▸ is the unicode right-pointing triangle, and %s is the section title in the Customizer */
958 printf( __( 'Customizing ▸ %s' ), esc_html( $this->manager->get_panel( 'nav_menus' )->title ) );
961 <?php _e( 'Add Menu Items' ); ?>
964 <div id="available-menu-items-search" class="accordion-section cannot-expand">
965 <div class="accordion-section-title">
966 <label class="screen-reader-text" for="menu-items-search"><?php _e( 'Search Menu Items' ); ?></label>
967 <input type="text" id="menu-items-search" placeholder="<?php esc_attr_e( 'Search menu items…' ) ?>" aria-describedby="menu-items-search-desc" />
968 <p class="screen-reader-text" id="menu-items-search-desc"><?php _e( 'The search results will be updated as you type.' ); ?></p>
969 <span class="spinner"></span>
971 <div class="search-icon" aria-hidden="true"></div>
972 <button type="button" class="clear-results"><span class="screen-reader-text"><?php _e( 'Clear Results' ); ?></span></button>
973 <ul class="accordion-section-content available-menu-items-list" data-type="search"></ul>
977 // Ensure the page post type comes first in the list.
978 $item_types = $this->available_item_types();
979 $page_item_type = null;
980 foreach ( $item_types as $i => $item_type ) {
981 if ( isset( $item_type['object'] ) && 'page' === $item_type['object'] ) {
982 $page_item_type = $item_type;
983 unset( $item_types[ $i ] );
987 $this->print_custom_links_available_menu_item();
988 if ( $page_item_type ) {
989 $this->print_post_type_container( $page_item_type );
991 // Containers for per-post-type item browsing; items are added with JS.
992 foreach ( $item_types as $item_type ) {
993 $this->print_post_type_container( $item_type );
996 </div><!-- #available-menu-items -->
1001 * Print the markup for new menu items.
1003 * To be used in the template #available-menu-items.
1008 * @param array $available_item_type Menu item data to output, including title, type, and label.
1011 protected function print_post_type_container( $available_item_type ) {
1012 $id = sprintf( 'available-menu-items-%s-%s', $available_item_type['type'], $available_item_type['object'] );
1014 <div id="<?php echo esc_attr( $id ); ?>" class="accordion-section">
1015 <h4 class="accordion-section-title" role="presentation">
1016 <?php echo esc_html( $available_item_type['title'] ); ?>
1017 <span class="spinner"></span>
1018 <span class="no-items"><?php _e( 'No items' ); ?></span>
1019 <button type="button" class="button-link" aria-expanded="false">
1020 <span class="screen-reader-text"><?php
1021 /* translators: %s: Title of a section with menu items */
1022 printf( __( 'Toggle section: %s' ), esc_html( $available_item_type['title'] ) ); ?></span>
1023 <span class="toggle-indicator" aria-hidden="true"></span>
1026 <div class="accordion-section-content">
1027 <?php if ( 'post_type' === $available_item_type['type'] ) : ?>
1028 <?php $post_type_obj = get_post_type_object( $available_item_type['object'] ); ?>
1029 <?php if ( current_user_can( $post_type_obj->cap->create_posts ) && current_user_can( $post_type_obj->cap->publish_posts ) ) : ?>
1030 <div class="new-content-item">
1031 <input type="text" class="create-item-input" placeholder="<?php echo esc_attr( $post_type_obj->labels->add_new_item ); ?>">
1032 <button type="button" class="button add-content"><?php _e( 'Add' ); ?></button>
1036 <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>
1043 * Print the markup for available menu item custom links.
1050 protected function print_custom_links_available_menu_item() {
1052 <div id="new-custom-menu-item" class="accordion-section">
1053 <h4 class="accordion-section-title" role="presentation">
1054 <?php _e( 'Custom Links' ); ?>
1055 <button type="button" class="button-link" aria-expanded="false">
1056 <span class="screen-reader-text"><?php _e( 'Toggle section: Custom Links' ); ?></span>
1057 <span class="toggle-indicator" aria-hidden="true"></span>
1060 <div class="accordion-section-content customlinkdiv">
1061 <input type="hidden" value="custom" id="custom-menu-item-type" name="menu-item[-1][menu-item-type]" />
1062 <p id="menu-item-url-wrap" class="wp-clearfix">
1063 <label class="howto" for="custom-menu-item-url"><?php _e( 'URL' ); ?></label>
1064 <input id="custom-menu-item-url" name="menu-item[-1][menu-item-url]" type="text" class="code menu-item-textbox" value="http://">
1066 <p id="menu-item-name-wrap" class="wp-clearfix">
1067 <label class="howto" for="custom-menu-item-name"><?php _e( 'Link Text' ); ?></label>
1068 <input id="custom-menu-item-name" name="menu-item[-1][menu-item-title]" type="text" class="regular-text menu-item-textbox">
1070 <p class="button-controls">
1071 <span class="add-to-menu">
1072 <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">
1073 <span class="spinner"></span>
1082 // Start functionality specific to partial-refresh of menu changes in Customizer preview.
1086 * Nav menu args used for each instance, keyed by the args HMAC.
1092 public $preview_nav_menu_instance_args = array();
1095 * Filters arguments for dynamic nav_menu selective refresh partials.
1100 * @param array|false $partial_args Partial args.
1101 * @param string $partial_id Partial ID.
1102 * @return array Partial args.
1104 public function customize_dynamic_partial_args( $partial_args, $partial_id ) {
1106 if ( preg_match( '/^nav_menu_instance\[[0-9a-f]{32}\]$/', $partial_id ) ) {
1107 if ( false === $partial_args ) {
1108 $partial_args = array();
1110 $partial_args = array_merge(
1113 'type' => 'nav_menu_instance',
1114 'render_callback' => array( $this, 'render_nav_menu_partial' ),
1115 'container_inclusive' => true,
1116 'settings' => array(), // Empty because the nav menu instance may relate to a menu or a location.
1117 'capability' => 'edit_theme_options',
1122 return $partial_args;
1126 * Add hooks for the Customizer preview.
1131 public function customize_preview_init() {
1132 add_action( 'wp_enqueue_scripts', array( $this, 'customize_preview_enqueue_deps' ) );
1133 add_filter( 'wp_nav_menu_args', array( $this, 'filter_wp_nav_menu_args' ), 1000 );
1134 add_filter( 'wp_nav_menu', array( $this, 'filter_wp_nav_menu' ), 10, 2 );
1135 add_filter( 'wp_footer', array( $this, 'export_preview_data' ), 1 );
1136 add_filter( 'customize_render_partials_response', array( $this, 'export_partial_rendered_nav_menu_instances' ) );
1140 * Make the auto-draft status protected so that it can be queried.
1145 public function make_auto_draft_status_previewable() {
1146 global $wp_post_statuses;
1147 $wp_post_statuses['auto-draft']->protected = true;
1151 * Sanitize post IDs for auto-draft posts created for nav menu items to be published.
1156 * @param array $value Post IDs.
1157 * @returns array Post IDs.
1159 public function sanitize_nav_menus_created_posts( $value ) {
1160 $post_ids = array();
1161 foreach ( wp_parse_id_list( $value ) as $post_id ) {
1162 if ( empty( $post_id ) ) {
1165 $post = get_post( $post_id );
1166 if ( 'auto-draft' !== $post->post_status ) {
1169 $post_type_obj = get_post_type_object( $post->post_type );
1170 if ( ! $post_type_obj ) {
1173 if ( ! current_user_can( $post_type_obj->cap->publish_posts ) || ! current_user_can( $post_type_obj->cap->edit_post, $post_id ) ) {
1176 $post_ids[] = $post->ID;
1182 * Publish the auto-draft posts that were created for nav menu items.
1184 * The post IDs will have been sanitized by already by
1185 * `WP_Customize_Nav_Menu_Items::sanitize_nav_menus_created_posts()` to
1186 * remove any post IDs for which the user cannot publish or for which the
1187 * post is not an auto-draft.
1192 * @param WP_Customize_Setting $setting Customizer setting object.
1194 public function save_nav_menus_created_posts( $setting ) {
1195 $post_ids = $setting->post_value();
1196 if ( ! empty( $post_ids ) ) {
1197 foreach ( $post_ids as $post_id ) {
1198 $target_status = 'attachment' === get_post_type( $post_id ) ? 'inherit' : 'publish';
1201 'post_status' => $target_status,
1203 $post_name = get_post_meta( $post_id, '_customize_draft_post_name', true );
1205 $args['post_name'] = $post_name;
1208 // Note that wp_publish_post() cannot be used because unique slugs need to be assigned.
1209 wp_update_post( wp_slash( $args ) );
1211 delete_post_meta( $post_id, '_customize_draft_post_name' );
1217 * Keep track of the arguments that are being passed to wp_nav_menu().
1221 * @see wp_nav_menu()
1222 * @see WP_Customize_Widgets_Partial_Refresh::filter_dynamic_sidebar_params()
1224 * @param array $args An array containing wp_nav_menu() arguments.
1225 * @return array Arguments.
1227 public function filter_wp_nav_menu_args( $args ) {
1229 * The following conditions determine whether or not this instance of
1230 * wp_nav_menu() can use selective refreshed. A wp_nav_menu() can be
1231 * selective refreshed if...
1233 $can_partial_refresh = (
1234 // ...if wp_nav_menu() is directly echoing out the menu (and thus isn't manipulating the string after generated),
1235 ! empty( $args['echo'] )
1237 // ...and if the fallback_cb can be serialized to JSON, since it will be included in the placement context data,
1238 ( empty( $args['fallback_cb'] ) || is_string( $args['fallback_cb'] ) )
1240 // ...and if the walker can also be serialized to JSON, since it will be included in the placement context data as well,
1241 ( empty( $args['walker'] ) || is_string( $args['walker'] ) )
1242 // ...and if it has a theme location assigned or an assigned menu to display,
1244 ! empty( $args['theme_location'] )
1246 ( ! empty( $args['menu'] ) && ( is_numeric( $args['menu'] ) || is_object( $args['menu'] ) ) )
1249 // ...and if the nav menu would be rendered with a wrapper container element (upon which to attach data-* attributes).
1251 ! empty( $args['container'] )
1253 ( isset( $args['items_wrap'] ) && '<' === substr( $args['items_wrap'], 0, 1 ) )
1256 $args['can_partial_refresh'] = $can_partial_refresh;
1258 $exported_args = $args;
1260 // Empty out args which may not be JSON-serializable.
1261 if ( ! $can_partial_refresh ) {
1262 $exported_args['fallback_cb'] = '';
1263 $exported_args['walker'] = '';
1267 * Replace object menu arg with a term_id menu arg, as this exports better
1268 * to JS and is easier to compare hashes.
1270 if ( ! empty( $exported_args['menu'] ) && is_object( $exported_args['menu'] ) ) {
1271 $exported_args['menu'] = $exported_args['menu']->term_id;
1274 ksort( $exported_args );
1275 $exported_args['args_hmac'] = $this->hash_nav_menu_args( $exported_args );
1277 $args['customize_preview_nav_menus_args'] = $exported_args;
1278 $this->preview_nav_menu_instance_args[ $exported_args['args_hmac'] ] = $exported_args;
1283 * Prepares wp_nav_menu() calls for partial refresh.
1285 * Injects attributes into container element.
1290 * @see wp_nav_menu()
1292 * @param string $nav_menu_content The HTML content for the navigation menu.
1293 * @param object $args An object containing wp_nav_menu() arguments.
1296 public function filter_wp_nav_menu( $nav_menu_content, $args ) {
1297 if ( isset( $args->customize_preview_nav_menus_args['can_partial_refresh'] ) && $args->customize_preview_nav_menus_args['can_partial_refresh'] ) {
1298 $attributes = sprintf( ' data-customize-partial-id="%s"', esc_attr( 'nav_menu_instance[' . $args->customize_preview_nav_menus_args['args_hmac'] . ']' ) );
1299 $attributes .= ' data-customize-partial-type="nav_menu_instance"';
1300 $attributes .= sprintf( ' data-customize-partial-placement-context="%s"', esc_attr( wp_json_encode( $args->customize_preview_nav_menus_args ) ) );
1301 $nav_menu_content = preg_replace( '#^(<\w+)#', '$1 ' . $attributes, $nav_menu_content, 1 );
1303 return $nav_menu_content;
1307 * Hashes (hmac) the nav menu arguments to ensure they are not tampered with when
1308 * submitted in the Ajax request.
1310 * Note that the array is expected to be pre-sorted.
1315 * @param array $args The arguments to hash.
1316 * @return string Hashed nav menu arguments.
1318 public function hash_nav_menu_args( $args ) {
1319 return wp_hash( serialize( $args ) );
1323 * Enqueue scripts for the Customizer preview.
1328 public function customize_preview_enqueue_deps() {
1329 wp_enqueue_script( 'customize-preview-nav-menus' ); // Note that we have overridden this.
1330 wp_enqueue_style( 'customize-preview' );
1334 * Exports data from PHP to JS.
1339 public function export_preview_data() {
1341 // Why not wp_localize_script? Because we're not localizing, and it forces values into strings.
1343 'navMenuInstanceArgs' => $this->preview_nav_menu_instance_args,
1345 printf( '<script>var _wpCustomizePreviewNavMenusExports = %s;</script>', wp_json_encode( $exports ) );
1349 * Export any wp_nav_menu() calls during the rendering of any partials.
1354 * @param array $response Response.
1355 * @return array Response.
1357 public function export_partial_rendered_nav_menu_instances( $response ) {
1358 $response['nav_menu_instance_args'] = $this->preview_nav_menu_instance_args;
1363 * Render a specific menu via wp_nav_menu() using the supplied arguments.
1368 * @see wp_nav_menu()
1370 * @param WP_Customize_Partial $partial Partial.
1371 * @param array $nav_menu_args Nav menu args supplied as container context.
1372 * @return string|false
1374 public function render_nav_menu_partial( $partial, $nav_menu_args ) {
1377 if ( ! isset( $nav_menu_args['args_hmac'] ) ) {
1378 // Error: missing_args_hmac.
1382 $nav_menu_args_hmac = $nav_menu_args['args_hmac'];
1383 unset( $nav_menu_args['args_hmac'] );
1385 ksort( $nav_menu_args );
1386 if ( ! hash_equals( $this->hash_nav_menu_args( $nav_menu_args ), $nav_menu_args_hmac ) ) {
1387 // Error: args_hmac_mismatch.
1392 wp_nav_menu( $nav_menu_args );
1393 $content = ob_get_clean();