[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

/wp-includes/ -> class-wp-customize-nav-menus.php (source)

   1  <?php
   2  /**
   3   * WordPress Customize Nav Menus classes
   4   *
   5   * @package WordPress
   6   * @subpackage Customize
   7   * @since 4.3.0
   8   */
   9  
  10  /**
  11   * Customize Nav Menus class.
  12   *
  13   * Implements menu management in the Customizer.
  14   *
  15   * @since 4.3.0
  16   *
  17   * @see WP_Customize_Manager
  18   */
  19  final class WP_Customize_Nav_Menus {
  20  
  21      /**
  22       * WP_Customize_Manager instance.
  23       *
  24       * @since 4.3.0
  25       * @var WP_Customize_Manager
  26       */
  27      public $manager;
  28  
  29      /**
  30       * Original nav menu locations before the theme was switched.
  31       *
  32       * @since 4.9.0
  33       * @var array
  34       */
  35      protected $original_nav_menu_locations;
  36  
  37      /**
  38       * Constructor.
  39       *
  40       * @since 4.3.0
  41       *
  42       * @param WP_Customize_Manager $manager Customizer bootstrap instance.
  43       */
  44  	public function __construct( $manager ) {
  45          $this->manager                     = $manager;
  46          $this->original_nav_menu_locations = get_nav_menu_locations();
  47  
  48          // See https://github.com/xwp/wp-customize-snapshots/blob/962586659688a5b1fd9ae93618b7ce2d4e7a421c/php/class-customize-snapshot-manager.php#L469-L499
  49          add_action( 'customize_register', array( $this, 'customize_register' ), 11 );
  50          add_filter( 'customize_dynamic_setting_args', array( $this, 'filter_dynamic_setting_args' ), 10, 2 );
  51          add_filter( 'customize_dynamic_setting_class', array( $this, 'filter_dynamic_setting_class' ), 10, 3 );
  52          add_action( 'customize_save_nav_menus_created_posts', array( $this, 'save_nav_menus_created_posts' ) );
  53  
  54          // Skip remaining hooks when the user can't manage nav menus anyway.
  55          if ( ! current_user_can( 'edit_theme_options' ) ) {
  56              return;
  57          }
  58  
  59          add_filter( 'customize_refresh_nonces', array( $this, 'filter_nonces' ) );
  60          add_action( 'wp_ajax_load-available-menu-items-customizer', array( $this, 'ajax_load_available_items' ) );
  61          add_action( 'wp_ajax_search-available-menu-items-customizer', array( $this, 'ajax_search_available_items' ) );
  62          add_action( 'wp_ajax_customize-nav-menus-insert-auto-draft', array( $this, 'ajax_insert_auto_draft_post' ) );
  63          add_action( 'customize_controls_enqueue_scripts', array( $this, 'enqueue_scripts' ) );
  64          add_action( 'customize_controls_print_footer_scripts', array( $this, 'print_templates' ) );
  65          add_action( 'customize_controls_print_footer_scripts', array( $this, 'available_items_template' ) );
  66          add_action( 'customize_preview_init', array( $this, 'customize_preview_init' ) );
  67          add_action( 'customize_preview_init', array( $this, 'make_auto_draft_status_previewable' ) );
  68  
  69          // Selective Refresh partials.
  70          add_filter( 'customize_dynamic_partial_args', array( $this, 'customize_dynamic_partial_args' ), 10, 2 );
  71      }
  72  
  73      /**
  74       * Adds a nonce for customizing menus.
  75       *
  76       * @since 4.5.0
  77       *
  78       * @param string[] $nonces Array of nonces.
  79       * @return string[] Modified array of nonces.
  80       */
  81  	public function filter_nonces( $nonces ) {
  82          $nonces['customize-menus'] = wp_create_nonce( 'customize-menus' );
  83          return $nonces;
  84      }
  85  
  86      /**
  87       * Ajax handler for loading available menu items.
  88       *
  89       * @since 4.3.0
  90       */
  91  	public function ajax_load_available_items() {
  92          check_ajax_referer( 'customize-menus', 'customize-menus-nonce' );
  93  
  94          if ( ! current_user_can( 'edit_theme_options' ) ) {
  95              wp_die( -1 );
  96          }
  97  
  98          $all_items  = array();
  99          $item_types = array();
 100          if ( isset( $_POST['item_types'] ) && is_array( $_POST['item_types'] ) ) {
 101              $item_types = wp_unslash( $_POST['item_types'] );
 102          } elseif ( isset( $_POST['type'] ) && isset( $_POST['object'] ) ) { // Back compat.
 103              $item_types[] = array(
 104                  'type'   => wp_unslash( $_POST['type'] ),
 105                  'object' => wp_unslash( $_POST['object'] ),
 106                  'page'   => empty( $_POST['page'] ) ? 0 : absint( $_POST['page'] ),
 107              );
 108          } else {
 109              wp_send_json_error( 'nav_menus_missing_type_or_object_parameter' );
 110          }
 111  
 112          foreach ( $item_types as $item_type ) {
 113              if ( empty( $item_type['type'] ) || empty( $item_type['object'] ) ) {
 114                  wp_send_json_error( 'nav_menus_missing_type_or_object_parameter' );
 115              }
 116              $type   = sanitize_key( $item_type['type'] );
 117              $object = sanitize_key( $item_type['object'] );
 118              $page   = empty( $item_type['page'] ) ? 0 : absint( $item_type['page'] );
 119              $items  = $this->load_available_items_query( $type, $object, $page );
 120              if ( is_wp_error( $items ) ) {
 121                  wp_send_json_error( $items->get_error_code() );
 122              }
 123              $all_items[ $item_type['type'] . ':' . $item_type['object'] ] = $items;
 124          }
 125  
 126          wp_send_json_success( array( 'items' => $all_items ) );
 127      }
 128  
 129      /**
 130       * Performs the post_type and taxonomy queries for loading available menu items.
 131       *
 132       * @since 4.3.0
 133       *
 134       * @param string $type   Optional. Accepts any custom object type and has built-in support for
 135       *                         'post_type' and 'taxonomy'. Default is 'post_type'.
 136       * @param string $object Optional. Accepts any registered taxonomy or post type name. Default is 'page'.
 137       * @param int    $page   Optional. The page number used to generate the query offset. Default is '0'.
 138       * @return array|WP_Error An array of menu items on success, a WP_Error object on failure.
 139       */
 140  	public function load_available_items_query( $type = 'post_type', $object = 'page', $page = 0 ) {
 141          $items = array();
 142  
 143          if ( 'post_type' === $type ) {
 144              $post_type = get_post_type_object( $object );
 145              if ( ! $post_type ) {
 146                  return new WP_Error( 'nav_menus_invalid_post_type' );
 147              }
 148  
 149              /*
 150               * If we're dealing with pages, let's prioritize the Front Page,
 151               * Posts Page and Privacy Policy Page at the top of the list.
 152               */
 153              $important_pages   = array();
 154              $suppress_page_ids = array();
 155              if ( 0 === $page && 'page' === $object ) {
 156                  // Insert Front Page or custom "Home" link.
 157                  $front_page = 'page' === get_option( 'show_on_front' ) ? (int) get_option( 'page_on_front' ) : 0;
 158                  if ( ! empty( $front_page ) ) {
 159                      $front_page_obj      = get_post( $front_page );
 160                      $important_pages[]   = $front_page_obj;
 161                      $suppress_page_ids[] = $front_page_obj->ID;
 162                  } else {
 163                      // Add "Home" link. Treat as a page, but switch to custom on add.
 164                      $items[] = array(
 165                          'id'         => 'home',
 166                          'title'      => _x( 'Home', 'nav menu home label' ),
 167                          'type'       => 'custom',
 168                          'type_label' => __( 'Custom Link' ),
 169                          'object'     => '',
 170                          'url'        => home_url(),
 171                      );
 172                  }
 173  
 174                  // Insert Posts Page.
 175                  $posts_page = 'page' === get_option( 'show_on_front' ) ? (int) get_option( 'page_for_posts' ) : 0;
 176                  if ( ! empty( $posts_page ) ) {
 177                      $posts_page_obj      = get_post( $posts_page );
 178                      $important_pages[]   = $posts_page_obj;
 179                      $suppress_page_ids[] = $posts_page_obj->ID;
 180                  }
 181  
 182                  // Insert Privacy Policy Page.
 183                  $privacy_policy_page_id = (int) get_option( 'wp_page_for_privacy_policy' );
 184                  if ( ! empty( $privacy_policy_page_id ) ) {
 185                      $privacy_policy_page = get_post( $privacy_policy_page_id );
 186                      if ( $privacy_policy_page instanceof WP_Post && 'publish' === $privacy_policy_page->post_status ) {
 187                          $important_pages[]   = $privacy_policy_page;
 188                          $suppress_page_ids[] = $privacy_policy_page->ID;
 189                      }
 190                  }
 191              } elseif ( 'post' !== $object && 0 === $page && $post_type->has_archive ) {
 192                  // Add a post type archive link.
 193                  $items[] = array(
 194                      'id'         => $object . '-archive',
 195                      'title'      => $post_type->labels->archives,
 196                      'type'       => 'post_type_archive',
 197                      'type_label' => __( 'Post Type Archive' ),
 198                      'object'     => $object,
 199                      'url'        => get_post_type_archive_link( $object ),
 200                  );
 201              }
 202  
 203              // Prepend posts with nav_menus_created_posts on first page.
 204              $posts = array();
 205              if ( 0 === $page && $this->manager->get_setting( 'nav_menus_created_posts' ) ) {
 206                  foreach ( $this->manager->get_setting( 'nav_menus_created_posts' )->value() as $post_id ) {
 207                      $auto_draft_post = get_post( $post_id );
 208                      if ( $post_type->name === $auto_draft_post->post_type ) {
 209                          $posts[] = $auto_draft_post;
 210                      }
 211                  }
 212              }
 213  
 214              $args = array(
 215                  'numberposts' => 10,
 216                  'offset'      => 10 * $page,
 217                  'orderby'     => 'date',
 218                  'order'       => 'DESC',
 219                  'post_type'   => $object,
 220              );
 221  
 222              // Add suppression array to arguments for get_posts.
 223              if ( ! empty( $suppress_page_ids ) ) {
 224                  $args['post__not_in'] = $suppress_page_ids;
 225              }
 226  
 227              $posts = array_merge(
 228                  $posts,
 229                  $important_pages,
 230                  get_posts( $args )
 231              );
 232  
 233              foreach ( $posts as $post ) {
 234                  $post_title = $post->post_title;
 235                  if ( '' === $post_title ) {
 236                      /* translators: %d: ID of a post. */
 237                      $post_title = sprintf( __( '#%d (no title)' ), $post->ID );
 238                  }
 239  
 240                  $post_type_label = get_post_type_object( $post->post_type )->labels->singular_name;
 241                  $post_states     = get_post_states( $post );
 242                  if ( ! empty( $post_states ) ) {
 243                      $post_type_label = implode( ',', $post_states );
 244                  }
 245  
 246                  $items[] = array(
 247                      'id'         => "post-{$post->ID}",
 248                      'title'      => html_entity_decode( $post_title, ENT_QUOTES, get_bloginfo( 'charset' ) ),
 249                      'type'       => 'post_type',
 250                      'type_label' => $post_type_label,
 251                      'object'     => $post->post_type,
 252                      'object_id'  => intval( $post->ID ),
 253                      'url'        => get_permalink( intval( $post->ID ) ),
 254                  );
 255              }
 256          } elseif ( 'taxonomy' === $type ) {
 257              $terms = get_terms(
 258                  array(
 259                      'taxonomy'     => $object,
 260                      'child_of'     => 0,
 261                      'exclude'      => '',
 262                      'hide_empty'   => false,
 263                      'hierarchical' => 1,
 264                      'include'      => '',
 265                      'number'       => 10,
 266                      'offset'       => 10 * $page,
 267                      'order'        => 'DESC',
 268                      'orderby'      => 'count',
 269                      'pad_counts'   => false,
 270                  )
 271              );
 272  
 273              if ( is_wp_error( $terms ) ) {
 274                  return $terms;
 275              }
 276  
 277              foreach ( $terms as $term ) {
 278                  $items[] = array(
 279                      'id'         => "term-{$term->term_id}",
 280                      'title'      => html_entity_decode( $term->name, ENT_QUOTES, get_bloginfo( 'charset' ) ),
 281                      'type'       => 'taxonomy',
 282                      'type_label' => get_taxonomy( $term->taxonomy )->labels->singular_name,
 283                      'object'     => $term->taxonomy,
 284                      'object_id'  => intval( $term->term_id ),
 285                      'url'        => get_term_link( intval( $term->term_id ), $term->taxonomy ),
 286                  );
 287              }
 288          }
 289  
 290          /**
 291           * Filters the available menu items.
 292           *
 293           * @since 4.3.0
 294           *
 295           * @param array  $items  The array of menu items.
 296           * @param string $type   The object type.
 297           * @param string $object The object name.
 298           * @param int    $page   The current page number.
 299           */
 300          $items = apply_filters( 'customize_nav_menu_available_items', $items, $type, $object, $page );
 301  
 302          return $items;
 303      }
 304  
 305      /**
 306       * Ajax handler for searching available menu items.
 307       *
 308       * @since 4.3.0
 309       */
 310  	public function ajax_search_available_items() {
 311          check_ajax_referer( 'customize-menus', 'customize-menus-nonce' );
 312  
 313          if ( ! current_user_can( 'edit_theme_options' ) ) {
 314              wp_die( -1 );
 315          }
 316  
 317          if ( empty( $_POST['search'] ) ) {
 318              wp_send_json_error( 'nav_menus_missing_search_parameter' );
 319          }
 320  
 321          $p = isset( $_POST['page'] ) ? absint( $_POST['page'] ) : 0;
 322          if ( $p < 1 ) {
 323              $p = 1;
 324          }
 325  
 326          $s     = sanitize_text_field( wp_unslash( $_POST['search'] ) );
 327          $items = $this->search_available_items_query(
 328              array(
 329                  'pagenum' => $p,
 330                  's'       => $s,
 331              )
 332          );
 333  
 334          if ( empty( $items ) ) {
 335              wp_send_json_error( array( 'message' => __( 'No results found.' ) ) );
 336          } else {
 337              wp_send_json_success( array( 'items' => $items ) );
 338          }
 339      }
 340  
 341      /**
 342       * Performs post queries for available-item searching.
 343       *
 344       * Based on WP_Editor::wp_link_query().
 345       *
 346       * @since 4.3.0
 347       *
 348       * @param array $args Optional. Accepts 'pagenum' and 's' (search) arguments.
 349       * @return array Menu items.
 350       */
 351  	public function search_available_items_query( $args = array() ) {
 352          $items = array();
 353  
 354          $post_type_objects = get_post_types( array( 'show_in_nav_menus' => true ), 'objects' );
 355          $query             = array(
 356              'post_type'              => array_keys( $post_type_objects ),
 357              'suppress_filters'       => true,
 358              'update_post_term_cache' => false,
 359              'update_post_meta_cache' => false,
 360              'post_status'            => 'publish',
 361              'posts_per_page'         => 20,
 362          );
 363  
 364          $args['pagenum'] = isset( $args['pagenum'] ) ? absint( $args['pagenum'] ) : 1;
 365          $query['offset'] = $args['pagenum'] > 1 ? $query['posts_per_page'] * ( $args['pagenum'] - 1 ) : 0;
 366  
 367          if ( isset( $args['s'] ) ) {
 368              $query['s'] = $args['s'];
 369          }
 370  
 371          $posts = array();
 372  
 373          // Prepend list of posts with nav_menus_created_posts search results on first page.
 374          $nav_menus_created_posts_setting = $this->manager->get_setting( 'nav_menus_created_posts' );
 375          if ( 1 === $args['pagenum'] && $nav_menus_created_posts_setting && count( $nav_menus_created_posts_setting->value() ) > 0 ) {
 376              $stub_post_query = new WP_Query(
 377                  array_merge(
 378                      $query,
 379                      array(
 380                          'post_status'    => 'auto-draft',
 381                          'post__in'       => $nav_menus_created_posts_setting->value(),
 382                          'posts_per_page' => -1,
 383                      )
 384                  )
 385              );
 386              $posts           = array_merge( $posts, $stub_post_query->posts );
 387          }
 388  
 389          // Query posts.
 390          $get_posts = new WP_Query( $query );
 391          $posts     = array_merge( $posts, $get_posts->posts );
 392  
 393          // Create items for posts.
 394          foreach ( $posts as $post ) {
 395              $post_title = $post->post_title;
 396              if ( '' === $post_title ) {
 397                  /* translators: %d: ID of a post. */
 398                  $post_title = sprintf( __( '#%d (no title)' ), $post->ID );
 399              }
 400  
 401              $post_type_label = $post_type_objects[ $post->post_type ]->labels->singular_name;
 402              $post_states     = get_post_states( $post );
 403              if ( ! empty( $post_states ) ) {
 404                  $post_type_label = implode( ',', $post_states );
 405              }
 406  
 407              $items[] = array(
 408                  'id'         => 'post-' . $post->ID,
 409                  'title'      => html_entity_decode( $post_title, ENT_QUOTES, get_bloginfo( 'charset' ) ),
 410                  'type'       => 'post_type',
 411                  'type_label' => $post_type_label,
 412                  'object'     => $post->post_type,
 413                  'object_id'  => intval( $post->ID ),
 414                  'url'        => get_permalink( intval( $post->ID ) ),
 415              );
 416          }
 417  
 418          // Query taxonomy terms.
 419          $taxonomies = get_taxonomies( array( 'show_in_nav_menus' => true ), 'names' );
 420          $terms      = get_terms(
 421              array(
 422                  'taxonomies' => $taxonomies,
 423                  'name__like' => $args['s'],
 424                  'number'     => 20,
 425                  'hide_empty' => false,
 426                  'offset'     => 20 * ( $args['pagenum'] - 1 ),
 427              )
 428          );
 429  
 430          // Check if any taxonomies were found.
 431          if ( ! empty( $terms ) ) {
 432              foreach ( $terms as $term ) {
 433                  $items[] = array(
 434                      'id'         => 'term-' . $term->term_id,
 435                      'title'      => html_entity_decode( $term->name, ENT_QUOTES, get_bloginfo( 'charset' ) ),
 436                      'type'       => 'taxonomy',
 437                      'type_label' => get_taxonomy( $term->taxonomy )->labels->singular_name,
 438                      'object'     => $term->taxonomy,
 439                      'object_id'  => intval( $term->term_id ),
 440                      'url'        => get_term_link( intval( $term->term_id ), $term->taxonomy ),
 441                  );
 442              }
 443          }
 444  
 445          // Add "Home" link if search term matches. Treat as a page, but switch to custom on add.
 446          if ( isset( $args['s'] ) ) {
 447              // Only insert custom "Home" link if there's no Front Page
 448              $front_page = 'page' === get_option( 'show_on_front' ) ? (int) get_option( 'page_on_front' ) : 0;
 449              if ( empty( $front_page ) ) {
 450                  $title   = _x( 'Home', 'nav menu home label' );
 451                  $matches = function_exists( 'mb_stripos' ) ? false !== mb_stripos( $title, $args['s'] ) : false !== stripos( $title, $args['s'] );
 452                  if ( $matches ) {
 453                      $items[] = array(
 454                          'id'         => 'home',
 455                          'title'      => $title,
 456                          'type'       => 'custom',
 457                          'type_label' => __( 'Custom Link' ),
 458                          'object'     => '',
 459                          'url'        => home_url(),
 460                      );
 461                  }
 462              }
 463          }
 464  
 465          /**
 466           * Filters the available menu items during a search request.
 467           *
 468           * @since 4.5.0
 469           *
 470           * @param array $items The array of menu items.
 471           * @param array $args  Includes 'pagenum' and 's' (search) arguments.
 472           */
 473          $items = apply_filters( 'customize_nav_menu_searched_items', $items, $args );
 474  
 475          return $items;
 476      }
 477  
 478      /**
 479       * Enqueue scripts and styles for Customizer pane.
 480       *
 481       * @since 4.3.0
 482       */
 483  	public function enqueue_scripts() {
 484          wp_enqueue_style( 'customize-nav-menus' );
 485          wp_enqueue_script( 'customize-nav-menus' );
 486  
 487          $temp_nav_menu_setting      = new WP_Customize_Nav_Menu_Setting( $this->manager, 'nav_menu[-1]' );
 488          $temp_nav_menu_item_setting = new WP_Customize_Nav_Menu_Item_Setting( $this->manager, 'nav_menu_item[-1]' );
 489  
 490          $num_locations = count( get_registered_nav_menus() );
 491          if ( 1 === $num_locations ) {
 492              $locations_description = __( 'Your theme can display menus in one location.' );
 493          } else {
 494              /* translators: %s: Number of menu locations. */
 495              $locations_description = sprintf( _n( 'Your theme can display menus in %s location.', 'Your theme can display menus in %s locations.', $num_locations ), number_format_i18n( $num_locations ) );
 496          }
 497  
 498          // Pass data to JS.
 499          $settings = array(
 500              'allMenus'                 => wp_get_nav_menus(),
 501              'itemTypes'                => $this->available_item_types(),
 502              'l10n'                     => array(
 503                  'untitled'               => _x( '(no label)', 'missing menu item navigation label' ),
 504                  'unnamed'                => _x( '(unnamed)', 'Missing menu name.' ),
 505                  'custom_label'           => __( 'Custom Link' ),
 506                  'page_label'             => get_post_type_object( 'page' )->labels->singular_name,
 507                  /* translators: %s: Menu location. */
 508                  'menuLocation'           => _x( '(Currently set to: %s)', 'menu' ),
 509                  'locationsTitle'         => 1 === $num_locations ? __( 'Menu Location' ) : __( 'Menu Locations' ),
 510                  'locationsDescription'   => $locations_description,
 511                  'menuNameLabel'          => __( 'Menu Name' ),
 512                  'newMenuNameDescription' => __( 'If your theme has multiple menus, giving them clear names will help you manage them.' ),
 513                  'itemAdded'              => __( 'Menu item added' ),
 514                  'itemDeleted'            => __( 'Menu item deleted' ),
 515                  'menuAdded'              => __( 'Menu created' ),
 516                  'menuDeleted'            => __( 'Menu deleted' ),
 517                  'movedUp'                => __( 'Menu item moved up' ),
 518                  'movedDown'              => __( 'Menu item moved down' ),
 519                  'movedLeft'              => __( 'Menu item moved out of submenu' ),
 520                  'movedRight'             => __( 'Menu item is now a sub-item' ),
 521                  /* translators: &#9656; is the unicode right-pointing triangle. %s: Section title in the Customizer. */
 522                  'customizingMenus'       => sprintf( __( 'Customizing &#9656; %s' ), esc_html( $this->manager->get_panel( 'nav_menus' )->title ) ),
 523                  /* translators: %s: Title of an invalid menu item. */
 524                  'invalidTitleTpl'        => __( '%s (Invalid)' ),
 525                  /* translators: %s: Title of a menu item in draft status. */
 526                  'pendingTitleTpl'        => __( '%s (Pending)' ),
 527                  /* translators: %d: Number of menu items found. */
 528                  'itemsFound'             => __( 'Number of items found: %d' ),
 529                  /* translators: %d: Number of additional menu items found. */
 530                  'itemsFoundMore'         => __( 'Additional items found: %d' ),
 531                  'itemsLoadingMore'       => __( 'Loading more results... please wait.' ),
 532                  'reorderModeOn'          => __( 'Reorder mode enabled' ),
 533                  'reorderModeOff'         => __( 'Reorder mode closed' ),
 534                  'reorderLabelOn'         => esc_attr__( 'Reorder menu items' ),
 535                  'reorderLabelOff'        => esc_attr__( 'Close reorder mode' ),
 536              ),
 537              'settingTransport'         => 'postMessage',
 538              'phpIntMax'                => PHP_INT_MAX,
 539              'defaultSettingValues'     => array(
 540                  'nav_menu'      => $temp_nav_menu_setting->default,
 541                  'nav_menu_item' => $temp_nav_menu_item_setting->default,
 542              ),
 543              'locationSlugMappedToName' => get_registered_nav_menus(),
 544          );
 545  
 546          $data = sprintf( 'var _wpCustomizeNavMenusSettings = %s;', wp_json_encode( $settings ) );
 547          wp_scripts()->add_data( 'customize-nav-menus', 'data', $data );
 548  
 549          // This is copied from nav-menus.php, and it has an unfortunate object name of `menus`.
 550          $nav_menus_l10n = array(
 551              'oneThemeLocationNoMenus' => null,
 552              'moveUp'                  => __( 'Move up one' ),
 553              'moveDown'                => __( 'Move down one' ),
 554              'moveToTop'               => __( 'Move to the top' ),
 555              /* translators: %s: Previous item name. */
 556              'moveUnder'               => __( 'Move under %s' ),
 557              /* translators: %s: Previous item name. */
 558              'moveOutFrom'             => __( 'Move out from under %s' ),
 559              /* translators: %s: Previous item name. */
 560              'under'                   => __( 'Under %s' ),
 561              /* translators: %s: Previous item name. */
 562              'outFrom'                 => __( 'Out from under %s' ),
 563              /* translators: 1: Item name, 2: Item position, 3: Total number of items. */
 564              'menuFocus'               => __( '%1$s. Menu item %2$d of %3$d.' ),
 565              /* translators: 1: Item name, 2: Item position, 3: Parent item name. */
 566              'subMenuFocus'            => __( '%1$s. Sub item number %2$d under %3$s.' ),
 567          );
 568          wp_localize_script( 'nav-menu', 'menus', $nav_menus_l10n );
 569      }
 570  
 571      /**
 572       * Filters a dynamic setting's constructor args.
 573       *
 574       * For a dynamic setting to be registered, this filter must be employed
 575       * to override the default false value with an array of args to pass to
 576       * the WP_Customize_Setting constructor.
 577       *
 578       * @since 4.3.0
 579       *
 580       * @param false|array $setting_args The arguments to the WP_Customize_Setting constructor.
 581       * @param string      $setting_id   ID for dynamic setting, usually coming from `$_POST['customized']`.
 582       * @return array|false
 583       */
 584  	public function filter_dynamic_setting_args( $setting_args, $setting_id ) {
 585          if ( preg_match( WP_Customize_Nav_Menu_Setting::ID_PATTERN, $setting_id ) ) {
 586              $setting_args = array(
 587                  'type'      => WP_Customize_Nav_Menu_Setting::TYPE,
 588                  'transport' => 'postMessage',
 589              );
 590          } elseif ( preg_match( WP_Customize_Nav_Menu_Item_Setting::ID_PATTERN, $setting_id ) ) {
 591              $setting_args = array(
 592                  'type'      => WP_Customize_Nav_Menu_Item_Setting::TYPE,
 593                  'transport' => 'postMessage',
 594              );
 595          }
 596          return $setting_args;
 597      }
 598  
 599      /**
 600       * Allow non-statically created settings to be constructed with custom WP_Customize_Setting subclass.
 601       *
 602       * @since 4.3.0
 603       *
 604       * @param string $setting_class WP_Customize_Setting or a subclass.
 605       * @param string $setting_id    ID for dynamic setting, usually coming from `$_POST['customized']`.
 606       * @param array  $setting_args  WP_Customize_Setting or a subclass.
 607       * @return string
 608       */
 609  	public function filter_dynamic_setting_class( $setting_class, $setting_id, $setting_args ) {
 610          unset( $setting_id );
 611  
 612          if ( ! empty( $setting_args['type'] ) && WP_Customize_Nav_Menu_Setting::TYPE === $setting_args['type'] ) {
 613              $setting_class = 'WP_Customize_Nav_Menu_Setting';
 614          } elseif ( ! empty( $setting_args['type'] ) && WP_Customize_Nav_Menu_Item_Setting::TYPE === $setting_args['type'] ) {
 615              $setting_class = 'WP_Customize_Nav_Menu_Item_Setting';
 616          }
 617          return $setting_class;
 618      }
 619  
 620      /**
 621       * Add the customizer settings and controls.
 622       *
 623       * @since 4.3.0
 624       */
 625  	public function customize_register() {
 626          $changeset = $this->manager->unsanitized_post_values();
 627  
 628          // Preview settings for nav menus early so that the sections and controls will be added properly.
 629          $nav_menus_setting_ids = array();
 630          foreach ( array_keys( $changeset ) as $setting_id ) {
 631              if ( preg_match( '/^(nav_menu_locations|nav_menu|nav_menu_item)\[/', $setting_id ) ) {
 632                  $nav_menus_setting_ids[] = $setting_id;
 633              }
 634          }
 635          $settings = $this->manager->add_dynamic_settings( $nav_menus_setting_ids );
 636          if ( $this->manager->settings_previewed() ) {
 637              foreach ( $settings as $setting ) {
 638                  $setting->preview();
 639              }
 640          }
 641  
 642          // Require JS-rendered control types.
 643          $this->manager->register_panel_type( 'WP_Customize_Nav_Menus_Panel' );
 644          $this->manager->register_control_type( 'WP_Customize_Nav_Menu_Control' );
 645          $this->manager->register_control_type( 'WP_Customize_Nav_Menu_Name_Control' );
 646          $this->manager->register_control_type( 'WP_Customize_Nav_Menu_Locations_Control' );
 647          $this->manager->register_control_type( 'WP_Customize_Nav_Menu_Auto_Add_Control' );
 648          $this->manager->register_control_type( 'WP_Customize_Nav_Menu_Item_Control' );
 649  
 650          // Create a panel for Menus.
 651          $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>';
 652          if ( current_theme_supports( 'widgets' ) ) {
 653              $description .= '<p>' . sprintf(
 654                  /* translators: %s: URL to the Widgets panel of the Customizer. */
 655                  __( 'Menus can be displayed in locations defined by your theme or in <a href="%s">widget areas</a> by adding a &#8220;Navigation Menu&#8221; widget.' ),
 656                  "javascript:wp.customize.panel( 'widgets' ).focus();"
 657              ) . '</p>';
 658          } else {
 659              $description .= '<p>' . __( 'Menus can be displayed in locations defined by your theme.' ) . '</p>';
 660          }
 661  
 662          /*
 663           * Once multiple theme supports are allowed in WP_Customize_Panel,
 664           * this panel can be restricted to themes that support menus or widgets.
 665           */
 666          $this->manager->add_panel(
 667              new WP_Customize_Nav_Menus_Panel(
 668                  $this->manager,
 669                  'nav_menus',
 670                  array(
 671                      'title'       => __( 'Menus' ),
 672                      'description' => $description,
 673                      'priority'    => 100,
 674                  )
 675              )
 676          );
 677          $menus = wp_get_nav_menus();
 678  
 679          // Menu locations.
 680          $locations     = get_registered_nav_menus();
 681          $num_locations = count( $locations );
 682          if ( 1 == $num_locations ) {
 683              $description = '<p>' . __( 'Your theme can display menus in one location. Select which menu you would like to use.' ) . '</p>';
 684          } else {
 685              /* translators: %s: Number of menu locations. */
 686              $description = '<p>' . sprintf( _n( 'Your theme can display menus in %s location. Select which menu you would like to use.', 'Your theme can display menus in %s locations. Select which menu appears in each location.', $num_locations ), number_format_i18n( $num_locations ) ) . '</p>';
 687          }
 688  
 689          if ( current_theme_supports( 'widgets' ) ) {
 690              /* translators: URL to the Widgets panel of the Customizer. */
 691              $description .= '<p>' . sprintf( __( 'If your theme has widget areas, you can also add menus there. Visit the <a href="%s">Widgets panel</a> and add a &#8220;Navigation Menu widget&#8221; to display a menu in a sidebar or footer.' ), "javascript:wp.customize.panel( 'widgets' ).focus();" ) . '</p>';
 692          }
 693  
 694          $this->manager->add_section(
 695              'menu_locations',
 696              array(
 697                  'title'       => 1 === $num_locations ? _x( 'View Location', 'menu locations' ) : _x( 'View All Locations', 'menu locations' ),
 698                  'panel'       => 'nav_menus',
 699                  'priority'    => 30,
 700                  'description' => $description,
 701              )
 702          );
 703  
 704          $choices = array( '0' => __( '&mdash; Select &mdash;' ) );
 705          foreach ( $menus as $menu ) {
 706              $choices[ $menu->term_id ] = wp_html_excerpt( $menu->name, 40, '&hellip;' );
 707          }
 708  
 709          // Attempt to re-map the nav menu location assignments when previewing a theme switch.
 710          $mapped_nav_menu_locations = array();
 711          if ( ! $this->manager->is_theme_active() ) {
 712              $theme_mods = get_option( 'theme_mods_' . $this->manager->get_stylesheet(), array() );
 713  
 714              // If there is no data from a previous activation, start fresh.
 715              if ( empty( $theme_mods['nav_menu_locations'] ) ) {
 716                  $theme_mods['nav_menu_locations'] = array();
 717              }
 718  
 719              $mapped_nav_menu_locations = wp_map_nav_menu_locations( $theme_mods['nav_menu_locations'], $this->original_nav_menu_locations );
 720          }
 721  
 722          foreach ( $locations as $location => $description ) {
 723              $setting_id = "nav_menu_locations[{$location}]";
 724  
 725              $setting = $this->manager->get_setting( $setting_id );
 726              if ( $setting ) {
 727                  $setting->transport = 'postMessage';
 728                  remove_filter( "customize_sanitize_{$setting_id}", 'absint' );
 729                  add_filter( "customize_sanitize_{$setting_id}", array( $this, 'intval_base10' ) );
 730              } else {
 731                  $this->manager->add_setting(
 732                      $setting_id,
 733                      array(
 734                          'sanitize_callback' => array( $this, 'intval_base10' ),
 735                          'theme_supports'    => 'menus',
 736                          'type'              => 'theme_mod',
 737                          'transport'         => 'postMessage',
 738                          'default'           => 0,
 739                      )
 740                  );
 741              }
 742  
 743              // Override the assigned nav menu location if mapped during previewed theme switch.
 744              if ( empty( $changeset[ $setting_id ] ) && isset( $mapped_nav_menu_locations[ $location ] ) ) {
 745                  $this->manager->set_post_value( $setting_id, $mapped_nav_menu_locations[ $location ] );
 746              }
 747  
 748              $this->manager->add_control(
 749                  new WP_Customize_Nav_Menu_Location_Control(
 750                      $this->manager,
 751                      $setting_id,
 752                      array(
 753                          'label'       => $description,
 754                          'location_id' => $location,
 755                          'section'     => 'menu_locations',
 756                          'choices'     => $choices,
 757                      )
 758                  )
 759              );
 760          }
 761  
 762          // Used to denote post states for special pages.
 763          if ( ! function_exists( 'get_post_states' ) ) {
 764              require_once  ABSPATH . 'wp-admin/includes/template.php';
 765          }
 766  
 767          // Register each menu as a Customizer section, and add each menu item to each menu.
 768          foreach ( $menus as $menu ) {
 769              $menu_id = $menu->term_id;
 770  
 771              // Create a section for each menu.
 772              $section_id = 'nav_menu[' . $menu_id . ']';
 773              $this->manager->add_section(
 774                  new WP_Customize_Nav_Menu_Section(
 775                      $this->manager,
 776                      $section_id,
 777                      array(
 778                          'title'    => html_entity_decode( $menu->name, ENT_QUOTES, get_bloginfo( 'charset' ) ),
 779                          'priority' => 10,
 780                          'panel'    => 'nav_menus',
 781                      )
 782                  )
 783              );
 784  
 785              $nav_menu_setting_id = 'nav_menu[' . $menu_id . ']';
 786              $this->manager->add_setting(
 787                  new WP_Customize_Nav_Menu_Setting(
 788                      $this->manager,
 789                      $nav_menu_setting_id,
 790                      array(
 791                          'transport' => 'postMessage',
 792                      )
 793                  )
 794              );
 795  
 796              // Add the menu contents.
 797              $menu_items = (array) wp_get_nav_menu_items( $menu_id );
 798  
 799              foreach ( array_values( $menu_items ) as $i => $item ) {
 800  
 801                  // Create a setting for each menu item (which doesn't actually manage data, currently).
 802                  $menu_item_setting_id = 'nav_menu_item[' . $item->ID . ']';
 803  
 804                  $value = (array) $item;
 805                  if ( empty( $value['post_title'] ) ) {
 806                      $value['title'] = '';
 807                  }
 808  
 809                  $value['nav_menu_term_id'] = $menu_id;
 810                  $this->manager->add_setting(
 811                      new WP_Customize_Nav_Menu_Item_Setting(
 812                          $this->manager,
 813                          $menu_item_setting_id,
 814                          array(
 815                              'value'     => $value,
 816                              'transport' => 'postMessage',
 817                          )
 818                      )
 819                  );
 820  
 821                  // Create a control for each menu item.
 822                  $this->manager->add_control(
 823                      new WP_Customize_Nav_Menu_Item_Control(
 824                          $this->manager,
 825                          $menu_item_setting_id,
 826                          array(
 827                              'label'    => $item->title,
 828                              'section'  => $section_id,
 829                              'priority' => 10 + $i,
 830                          )
 831                      )
 832                  );
 833              }
 834  
 835              // Note: other controls inside of this section get added dynamically in JS via the MenuSection.ready() function.
 836          }
 837  
 838          // Add the add-new-menu section and controls.
 839          $this->manager->add_section(
 840              'add_menu',
 841              array(
 842                  'type'     => 'new_menu',
 843                  'title'    => __( 'New Menu' ),
 844                  'panel'    => 'nav_menus',
 845                  'priority' => 20,
 846              )
 847          );
 848  
 849          $this->manager->add_setting(
 850              new WP_Customize_Filter_Setting(
 851                  $this->manager,
 852                  'nav_menus_created_posts',
 853                  array(
 854                      'transport'         => 'postMessage',
 855                      'type'              => 'option', // To prevent theme prefix in changeset.
 856                      'default'           => array(),
 857                      'sanitize_callback' => array( $this, 'sanitize_nav_menus_created_posts' ),
 858                  )
 859              )
 860          );
 861      }
 862  
 863      /**
 864       * Get the base10 intval.
 865       *
 866       * This is used as a setting's sanitize_callback; we can't use just plain
 867       * intval because the second argument is not what intval() expects.
 868       *
 869       * @since 4.3.0
 870       *
 871       * @param mixed $value Number to convert.
 872       * @return int Integer.
 873       */
 874  	public function intval_base10( $value ) {
 875          return intval( $value, 10 );
 876      }
 877  
 878      /**
 879       * Return an array of all the available item types.
 880       *
 881       * @since 4.3.0
 882       * @since 4.7.0  Each array item now includes a `$type_label` in addition to `$title`, `$type`, and `$object`.
 883       *
 884       * @return array The available menu item types.
 885       */
 886  	public function available_item_types() {
 887          $item_types = array();
 888  
 889          $post_types = get_post_types( array( 'show_in_nav_menus' => true ), 'objects' );
 890          if ( $post_types ) {
 891              foreach ( $post_types as $slug => $post_type ) {
 892                  $item_types[] = array(
 893                      'title'      => $post_type->labels->name,
 894                      'type_label' => $post_type->labels->singular_name,
 895                      'type'       => 'post_type',
 896                      'object'     => $post_type->name,
 897                  );
 898              }
 899          }
 900  
 901          $taxonomies = get_taxonomies( array( 'show_in_nav_menus' => true ), 'objects' );
 902          if ( $taxonomies ) {
 903              foreach ( $taxonomies as $slug => $taxonomy ) {
 904                  if ( 'post_format' === $taxonomy && ! current_theme_supports( 'post-formats' ) ) {
 905                      continue;
 906                  }
 907                  $item_types[] = array(
 908                      'title'      => $taxonomy->labels->name,
 909                      'type_label' => $taxonomy->labels->singular_name,
 910                      'type'       => 'taxonomy',
 911                      'object'     => $taxonomy->name,
 912                  );
 913              }
 914          }
 915  
 916          /**
 917           * Filters the available menu item types.
 918           *
 919           * @since 4.3.0
 920           * @since 4.7.0  Each array item now includes a `$type_label` in addition to `$title`, `$type`, and `$object`.
 921           *
 922           * @param array $item_types Navigation menu item types.
 923           */
 924          $item_types = apply_filters( 'customize_nav_menu_available_item_types', $item_types );
 925  
 926          return $item_types;
 927      }
 928  
 929      /**
 930       * Add a new `auto-draft` post.
 931       *
 932       * @since 4.7.0
 933       *
 934       * @param array $postarr {
 935       *     Post array. Note that post_status is overridden to be `auto-draft`.
 936       *
 937       * @var string $post_title   Post title. Required.
 938       * @var string $post_type    Post type. Required.
 939       * @var string $post_name    Post name.
 940       * @var string $post_content Post content.
 941       * }
 942       * @return WP_Post|WP_Error Inserted auto-draft post object or error.
 943       */
 944  	public function insert_auto_draft_post( $postarr ) {
 945          if ( ! isset( $postarr['post_type'] ) ) {
 946              return new WP_Error( 'unknown_post_type', __( 'Invalid post type.' ) );
 947          }
 948          if ( empty( $postarr['post_title'] ) ) {
 949              return new WP_Error( 'empty_title', __( 'Empty title.' ) );
 950          }
 951          if ( ! empty( $postarr['post_status'] ) ) {
 952              return new WP_Error( 'status_forbidden', __( 'Status is forbidden.' ) );
 953          }
 954  
 955          /*
 956           * If the changeset is a draft, this will change to draft the next time the changeset
 957           * is updated; otherwise, auto-draft will persist in autosave revisions, until save.
 958           */
 959          $postarr['post_status'] = 'auto-draft';
 960  
 961          // Auto-drafts are allowed to have empty post_names, so it has to be explicitly set.
 962          if ( empty( $postarr['post_name'] ) ) {
 963              $postarr['post_name'] = sanitize_title( $postarr['post_title'] );
 964          }
 965          if ( ! isset( $postarr['meta_input'] ) ) {
 966              $postarr['meta_input'] = array();
 967          }
 968          $postarr['meta_input']['_customize_draft_post_name'] = $postarr['post_name'];
 969          $postarr['meta_input']['_customize_changeset_uuid']  = $this->manager->changeset_uuid();
 970          unset( $postarr['post_name'] );
 971  
 972          add_filter( 'wp_insert_post_empty_content', '__return_false', 1000 );
 973          $r = wp_insert_post( wp_slash( $postarr ), true );
 974          remove_filter( 'wp_insert_post_empty_content', '__return_false', 1000 );
 975  
 976          if ( is_wp_error( $r ) ) {
 977              return $r;
 978          } else {
 979              return get_post( $r );
 980          }
 981      }
 982  
 983      /**
 984       * Ajax handler for adding a new auto-draft post.
 985       *
 986       * @since 4.7.0
 987       */
 988  	public function ajax_insert_auto_draft_post() {
 989          if ( ! check_ajax_referer( 'customize-menus', 'customize-menus-nonce', false ) ) {
 990              wp_send_json_error( 'bad_nonce', 400 );
 991          }
 992  
 993          if ( ! current_user_can( 'customize' ) ) {
 994              wp_send_json_error( 'customize_not_allowed', 403 );
 995          }
 996  
 997          if ( empty( $_POST['params'] ) || ! is_array( $_POST['params'] ) ) {
 998              wp_send_json_error( 'missing_params', 400 );
 999          }
1000  
1001          $params         = wp_unslash( $_POST['params'] );
1002          $illegal_params = array_diff( array_keys( $params ), array( 'post_type', 'post_title' ) );
1003          if ( ! empty( $illegal_params ) ) {
1004              wp_send_json_error( 'illegal_params', 400 );
1005          }
1006  
1007          $params = array_merge(
1008              array(
1009                  'post_type'  => '',
1010                  'post_title' => '',
1011              ),
1012              $params
1013          );
1014  
1015          if ( empty( $params['post_type'] ) || ! post_type_exists( $params['post_type'] ) ) {
1016              status_header( 400 );
1017              wp_send_json_error( 'missing_post_type_param' );
1018          }
1019  
1020          $post_type_object = get_post_type_object( $params['post_type'] );
1021          if ( ! current_user_can( $post_type_object->cap->create_posts ) || ! current_user_can( $post_type_object->cap->publish_posts ) ) {
1022              status_header( 403 );
1023              wp_send_json_error( 'insufficient_post_permissions' );
1024          }
1025  
1026          $params['post_title'] = trim( $params['post_title'] );
1027          if ( '' === $params['post_title'] ) {
1028              status_header( 400 );
1029              wp_send_json_error( 'missing_post_title' );
1030          }
1031  
1032          $r = $this->insert_auto_draft_post( $params );
1033          if ( is_wp_error( $r ) ) {
1034              $error = $r;
1035              if ( ! empty( $post_type_object->labels->singular_name ) ) {
1036                  $singular_name = $post_type_object->labels->singular_name;
1037              } else {
1038                  $singular_name = __( 'Post' );
1039              }
1040  
1041              $data = array(
1042                  /* translators: 1: Post type name, 2: Error message. */
1043                  'message' => sprintf( __( '%1$s could not be created: %2$s' ), $singular_name, $error->get_error_message() ),
1044              );
1045              wp_send_json_error( $data );
1046          } else {
1047              $post = $r;
1048              $data = array(
1049                  'post_id' => $post->ID,
1050                  'url'     => get_permalink( $post->ID ),
1051              );
1052              wp_send_json_success( $data );
1053          }
1054      }
1055  
1056      /**
1057       * Print the JavaScript templates used to render Menu Customizer components.
1058       *
1059       * Templates are imported into the JS use wp.template.
1060       *
1061       * @since 4.3.0
1062       */
1063  	public function print_templates() {
1064          ?>
1065          <script type="text/html" id="tmpl-available-menu-item">
1066              <li id="menu-item-tpl-{{ data.id }}" class="menu-item-tpl" data-menu-item-id="{{ data.id }}">
1067                  <div class="menu-item-bar">
1068                      <div class="menu-item-handle">
1069                          <span class="item-type" aria-hidden="true">{{ data.type_label }}</span>
1070                          <span class="item-title" aria-hidden="true">
1071                              <span class="menu-item-title<# if ( ! data.title ) { #> no-title<# } #>">{{ data.title || wp.customize.Menus.data.l10n.untitled }}</span>
1072                          </span>
1073                          <button type="button" class="button-link item-add">
1074                              <span class="screen-reader-text">
1075                              <?php
1076                                  /* translators: 1: Title of a menu item, 2: Type of a menu item. */
1077                                  printf( __( 'Add to menu: %1$s (%2$s)' ), '{{ data.title || wp.customize.Menus.data.l10n.untitled }}', '{{ data.type_label }}' );
1078                              ?>
1079                              </span>
1080                          </button>
1081                      </div>
1082                  </div>
1083              </li>
1084          </script>
1085  
1086          <script type="text/html" id="tmpl-menu-item-reorder-nav">
1087              <div class="menu-item-reorder-nav">
1088                  <?php
1089                  printf(
1090                      '<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>',
1091                      __( 'Move up' ),
1092                      __( 'Move down' ),
1093                      __( 'Move one level up' ),
1094                      __( 'Move one level down' )
1095                  );
1096                  ?>
1097              </div>
1098          </script>
1099  
1100          <script type="text/html" id="tmpl-nav-menu-delete-button">
1101              <div class="menu-delete-item">
1102                  <button type="button" class="button-link button-link-delete">
1103                      <?php _e( 'Delete Menu' ); ?>
1104                  </button>
1105              </div>
1106          </script>
1107  
1108          <script type="text/html" id="tmpl-nav-menu-submit-new-button">
1109              <p id="customize-new-menu-submit-description"><?php _e( 'Click &#8220;Next&#8221; to start adding links to your new menu.' ); ?></p>
1110              <button id="customize-new-menu-submit" type="button" class="button" aria-describedby="customize-new-menu-submit-description"><?php _e( 'Next' ); ?></button>
1111          </script>
1112  
1113          <script type="text/html" id="tmpl-nav-menu-locations-header">
1114              <span class="customize-control-title customize-section-title-menu_locations-heading">{{ data.l10n.locationsTitle }}</span>
1115              <p class="customize-control-description customize-section-title-menu_locations-description">{{ data.l10n.locationsDescription }}</p>
1116          </script>
1117  
1118          <script type="text/html" id="tmpl-nav-menu-create-menu-section-title">
1119              <p class="add-new-menu-notice">
1120                  <?php _e( 'It doesn&#8217;t look like your site has any menus yet. Want to build one? Click the button to start.' ); ?>
1121              </p>
1122              <p class="add-new-menu-notice">
1123                  <?php _e( 'You&#8217;ll create a menu, assign it a location, and add menu items like links to pages and categories. If your theme has multiple menu areas, you might need to create more than one.' ); ?>
1124              </p>
1125              <h3>
1126                  <button type="button" class="button customize-add-menu-button">
1127                      <?php _e( 'Create New Menu' ); ?>
1128                  </button>
1129              </h3>
1130          </script>
1131          <?php
1132      }
1133  
1134      /**
1135       * Print the HTML template used to render the add-menu-item frame.
1136       *
1137       * @since 4.3.0
1138       */
1139  	public function available_items_template() {
1140          ?>
1141          <div id="available-menu-items" class="accordion-container">
1142              <div class="customize-section-title">
1143                  <button type="button" class="customize-section-back" tabindex="-1">
1144                      <span class="screen-reader-text"><?php _e( 'Back' ); ?></span>
1145                  </button>
1146                  <h3>
1147                      <span class="customize-action">
1148                          <?php
1149                              /* translators: &#9656; is the unicode right-pointing triangle. %s: Section title in the Customizer. */
1150                              printf( __( 'Customizing &#9656; %s' ), esc_html( $this->manager->get_panel( 'nav_menus' )->title ) );
1151                          ?>
1152                      </span>
1153                      <?php _e( 'Add Menu Items' ); ?>
1154                  </h3>
1155              </div>
1156              <div id="available-menu-items-search" class="accordion-section cannot-expand">
1157                  <div class="accordion-section-title">
1158                      <label class="screen-reader-text" for="menu-items-search"><?php _e( 'Search Menu Items' ); ?></label>
1159                      <input type="text" id="menu-items-search" placeholder="<?php esc_attr_e( 'Search menu items&hellip;' ); ?>" aria-describedby="menu-items-search-desc" />
1160                      <p class="screen-reader-text" id="menu-items-search-desc"><?php _e( 'The search results will be updated as you type.' ); ?></p>
1161                      <span class="spinner"></span>
1162                  </div>
1163                  <div class="search-icon" aria-hidden="true"></div>
1164                  <button type="button" class="clear-results"><span class="screen-reader-text"><?php _e( 'Clear Results' ); ?></span></button>
1165                  <ul class="accordion-section-content available-menu-items-list" data-type="search"></ul>
1166              </div>
1167              <?php
1168  
1169              // Ensure the page post type comes first in the list.
1170              $item_types     = $this->available_item_types();
1171              $page_item_type = null;
1172              foreach ( $item_types as $i => $item_type ) {
1173                  if ( isset( $item_type['object'] ) && 'page' === $item_type['object'] ) {
1174                      $page_item_type = $item_type;
1175                      unset( $item_types[ $i ] );
1176                  }
1177              }
1178  
1179              $this->print_custom_links_available_menu_item();
1180              if ( $page_item_type ) {
1181                  $this->print_post_type_container( $page_item_type );
1182              }
1183              // Containers for per-post-type item browsing; items are added with JS.
1184              foreach ( $item_types as $item_type ) {
1185                  $this->print_post_type_container( $item_type );
1186              }
1187              ?>
1188          </div><!-- #available-menu-items -->
1189          <?php
1190      }
1191  
1192      /**
1193       * Print the markup for new menu items.
1194       *
1195       * To be used in the template #available-menu-items.
1196       *
1197       * @since 4.7.0
1198       *
1199       * @param array $available_item_type Menu item data to output, including title, type, and label.
1200       * @return void
1201       */
1202  	protected function print_post_type_container( $available_item_type ) {
1203          $id = sprintf( 'available-menu-items-%s-%s', $available_item_type['type'], $available_item_type['object'] );
1204          ?>
1205          <div id="<?php echo esc_attr( $id ); ?>" class="accordion-section">
1206              <h4 class="accordion-section-title" role="presentation">
1207                  <?php echo esc_html( $available_item_type['title'] ); ?>
1208                  <span class="spinner"></span>
1209                  <span class="no-items"><?php _e( 'No items' ); ?></span>
1210                  <button type="button" class="button-link" aria-expanded="false">
1211                      <span class="screen-reader-text">
1212                      <?php
1213                          /* translators: %s: Title of a section with menu items. */
1214                          printf( __( 'Toggle section: %s' ), esc_html( $available_item_type['title'] ) );
1215                      ?>
1216                          </span>
1217                      <span class="toggle-indicator" aria-hidden="true"></span>
1218                  </button>
1219              </h4>
1220              <div class="accordion-section-content">
1221                  <?php if ( 'post_type' === $available_item_type['type'] ) : ?>
1222                      <?php $post_type_obj = get_post_type_object( $available_item_type['object'] ); ?>
1223                      <?php if ( current_user_can( $post_type_obj->cap->create_posts ) && current_user_can( $post_type_obj->cap->publish_posts ) ) : ?>
1224                          <div class="new-content-item">
1225                              <label for="<?php echo esc_attr( 'create-item-input-' . $available_item_type['object'] ); ?>" class="screen-reader-text"><?php echo esc_html( $post_type_obj->labels->add_new_item ); ?></label>
1226                              <input type="text" id="<?php echo esc_attr( 'create-item-input-' . $available_item_type['object'] ); ?>" class="create-item-input" placeholder="<?php echo esc_attr( $post_type_obj->labels->add_new_item ); ?>">
1227                              <button type="button" class="button add-content"><?php _e( 'Add' ); ?></button>
1228                          </div>
1229                      <?php endif; ?>
1230                  <?php endif; ?>
1231                  <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>
1232              </div>
1233          </div>
1234          <?php
1235      }
1236  
1237      /**
1238       * Print the markup for available menu item custom links.
1239       *
1240       * @since 4.7.0
1241       *
1242       * @return void
1243       */
1244  	protected function print_custom_links_available_menu_item() {
1245          ?>
1246          <div id="new-custom-menu-item" class="accordion-section">
1247              <h4 class="accordion-section-title" role="presentation">
1248                  <?php _e( 'Custom Links' ); ?>
1249                  <button type="button" class="button-link" aria-expanded="false">
1250                      <span class="screen-reader-text"><?php _e( 'Toggle section: Custom Links' ); ?></span>
1251                      <span class="toggle-indicator" aria-hidden="true"></span>
1252                  </button>
1253              </h4>
1254              <div class="accordion-section-content customlinkdiv">
1255                  <input type="hidden" value="custom" id="custom-menu-item-type" name="menu-item[-1][menu-item-type]" />
1256                  <p id="menu-item-url-wrap" class="wp-clearfix">
1257                      <label class="howto" for="custom-menu-item-url"><?php _e( 'URL' ); ?></label>
1258                      <input id="custom-menu-item-url" name="menu-item[-1][menu-item-url]" type="text" class="code menu-item-textbox" placeholder="https://">
1259                  </p>
1260                  <p id="menu-item-name-wrap" class="wp-clearfix">
1261                      <label class="howto" for="custom-menu-item-name"><?php _e( 'Link Text' ); ?></label>
1262                      <input id="custom-menu-item-name" name="menu-item[-1][menu-item-title]" type="text" class="regular-text menu-item-textbox">
1263                  </p>
1264                  <p class="button-controls">
1265                      <span class="add-to-menu">
1266                          <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">
1267                          <span class="spinner"></span>
1268                      </span>
1269                  </p>
1270              </div>
1271          </div>
1272          <?php
1273      }
1274  
1275      //
1276      // Start functionality specific to partial-refresh of menu changes in Customizer preview.
1277      //
1278  
1279      /**
1280       * Nav menu args used for each instance, keyed by the args HMAC.
1281       *
1282       * @since 4.3.0
1283       * @var array
1284       */
1285      public $preview_nav_menu_instance_args = array();
1286  
1287      /**
1288       * Filters arguments for dynamic nav_menu selective refresh partials.
1289       *
1290       * @since 4.5.0
1291       *
1292       * @param array|false $partial_args Partial args.
1293       * @param string      $partial_id   Partial ID.
1294       * @return array Partial args.
1295       */
1296  	public function customize_dynamic_partial_args( $partial_args, $partial_id ) {
1297  
1298          if ( preg_match( '/^nav_menu_instance\[[0-9a-f]{32}\]$/', $partial_id ) ) {
1299              if ( false === $partial_args ) {
1300                  $partial_args = array();
1301              }
1302              $partial_args = array_merge(
1303                  $partial_args,
1304                  array(
1305                      'type'                => 'nav_menu_instance',
1306                      'render_callback'     => array( $this, 'render_nav_menu_partial' ),
1307                      'container_inclusive' => true,
1308                      'settings'            => array(), // Empty because the nav menu instance may relate to a menu or a location.
1309                      'capability'          => 'edit_theme_options',
1310                  )
1311              );
1312          }
1313  
1314          return $partial_args;
1315      }
1316  
1317      /**
1318       * Add hooks for the Customizer preview.
1319       *
1320       * @since 4.3.0
1321       */
1322  	public function customize_preview_init() {
1323          add_action( 'wp_enqueue_scripts', array( $this, 'customize_preview_enqueue_deps' ) );
1324          add_filter( 'wp_nav_menu_args', array( $this, 'filter_wp_nav_menu_args' ), 1000 );
1325          add_filter( 'wp_nav_menu', array( $this, 'filter_wp_nav_menu' ), 10, 2 );
1326          add_filter( 'wp_footer', array( $this, 'export_preview_data' ), 1 );
1327          add_filter( 'customize_render_partials_response', array( $this, 'export_partial_rendered_nav_menu_instances' ) );
1328      }
1329  
1330      /**
1331       * Make the auto-draft status protected so that it can be queried.
1332       *
1333       * @since 4.7.0
1334       *
1335       * @global array $wp_post_statuses List of post statuses.
1336       */
1337  	public function make_auto_draft_status_previewable() {
1338          global $wp_post_statuses;
1339          $wp_post_statuses['auto-draft']->protected = true;
1340      }
1341  
1342      /**
1343       * Sanitize post IDs for posts created for nav menu items to be published.
1344       *
1345       * @since 4.7.0
1346       *
1347       * @param array $value Post IDs.
1348       * @return array Post IDs.
1349       */
1350  	public function sanitize_nav_menus_created_posts( $value ) {
1351          $post_ids = array();
1352          foreach ( wp_parse_id_list( $value ) as $post_id ) {
1353              if ( empty( $post_id ) ) {
1354                  continue;
1355              }
1356              $post = get_post( $post_id );
1357              if ( 'auto-draft' !== $post->post_status && 'draft' !== $post->post_status ) {
1358                  continue;
1359              }
1360              $post_type_obj = get_post_type_object( $post->post_type );
1361              if ( ! $post_type_obj ) {
1362                  continue;
1363              }
1364              if ( ! current_user_can( $post_type_obj->cap->publish_posts ) || ! current_user_can( 'edit_post', $post_id ) ) {
1365                  continue;
1366              }
1367              $post_ids[] = $post->ID;
1368          }
1369          return $post_ids;
1370      }
1371  
1372      /**
1373       * Publish the auto-draft posts that were created for nav menu items.
1374       *
1375       * The post IDs will have been sanitized by already by
1376       * `WP_Customize_Nav_Menu_Items::sanitize_nav_menus_created_posts()` to
1377       * remove any post IDs for which the user cannot publish or for which the
1378       * post is not an auto-draft.
1379       *
1380       * @since 4.7.0
1381       *
1382       * @param WP_Customize_Setting $setting Customizer setting object.
1383       */
1384  	public function save_nav_menus_created_posts( $setting ) {
1385          $post_ids = $setting->post_value();
1386          if ( ! empty( $post_ids ) ) {
1387              foreach ( $post_ids as $post_id ) {
1388  
1389                  // Prevent overriding the status that a user may have prematurely updated the post to.
1390                  $current_status = get_post_status( $post_id );
1391                  if ( 'auto-draft' !== $current_status && 'draft' !== $current_status ) {
1392                      continue;
1393                  }
1394  
1395                  $target_status = 'attachment' === get_post_type( $post_id ) ? 'inherit' : 'publish';
1396                  $args          = array(
1397                      'ID'          => $post_id,
1398                      'post_status' => $target_status,
1399                  );
1400                  $post_name     = get_post_meta( $post_id, '_customize_draft_post_name', true );
1401                  if ( $post_name ) {
1402                      $args['post_name'] = $post_name;
1403                  }
1404  
1405                  // Note that wp_publish_post() cannot be used because unique slugs need to be assigned.
1406                  wp_update_post( wp_slash( $args ) );
1407  
1408                  delete_post_meta( $post_id, '_customize_draft_post_name' );
1409              }
1410          }
1411      }
1412  
1413      /**
1414       * Keep track of the arguments that are being passed to wp_nav_menu().
1415       *
1416       * @since 4.3.0
1417       *
1418       * @see wp_nav_menu()
1419       * @see WP_Customize_Widgets::filter_dynamic_sidebar_params()
1420       *
1421       * @param array $args An array containing wp_nav_menu() arguments.
1422       * @return array Arguments.
1423       */
1424  	public function filter_wp_nav_menu_args( $args ) {
1425          /*
1426           * The following conditions determine whether or not this instance of
1427           * wp_nav_menu() can use selective refreshed. A wp_nav_menu() can be
1428           * selective refreshed if...
1429           */
1430          $can_partial_refresh = (
1431              // ...if wp_nav_menu() is directly echoing out the menu (and thus isn't manipulating the string after generated),
1432              ! empty( $args['echo'] )
1433              &&
1434              // ...and if the fallback_cb can be serialized to JSON, since it will be included in the placement context data,
1435              ( empty( $args['fallback_cb'] ) || is_string( $args['fallback_cb'] ) )
1436              &&
1437              // ...and if the walker can also be serialized to JSON, since it will be included in the placement context data as well,
1438              ( empty( $args['walker'] ) || is_string( $args['walker'] ) )
1439              // ...and if it has a theme location assigned or an assigned menu to display,
1440              && (
1441                  ! empty( $args['theme_location'] )
1442                  ||
1443                  ( ! empty( $args['menu'] ) && ( is_numeric( $args['menu'] ) || is_object( $args['menu'] ) ) )
1444              )
1445              &&
1446              // ...and if the nav menu would be rendered with a wrapper container element (upon which to attach data-* attributes).
1447              (
1448                  ! empty( $args['container'] )
1449                  ||
1450                  ( isset( $args['items_wrap'] ) && '<' === substr( $args['items_wrap'], 0, 1 ) )
1451              )
1452          );
1453          $args['can_partial_refresh'] = $can_partial_refresh;
1454  
1455          $exported_args = $args;
1456  
1457          // Empty out args which may not be JSON-serializable.
1458          if ( ! $can_partial_refresh ) {
1459              $exported_args['fallback_cb'] = '';
1460              $exported_args['walker']      = '';
1461          }
1462  
1463          /*
1464           * Replace object menu arg with a term_id menu arg, as this exports better
1465           * to JS and is easier to compare hashes.
1466           */
1467          if ( ! empty( $exported_args['menu'] ) && is_object( $exported_args['menu'] ) ) {
1468              $exported_args['menu'] = $exported_args['menu']->term_id;
1469          }
1470  
1471          ksort( $exported_args );
1472          $exported_args['args_hmac'] = $this->hash_nav_menu_args( $exported_args );
1473  
1474          $args['customize_preview_nav_menus_args']                            = $exported_args;
1475          $this->preview_nav_menu_instance_args[ $exported_args['args_hmac'] ] = $exported_args;
1476          return $args;
1477      }
1478  
1479      /**
1480       * Prepares wp_nav_menu() calls for partial refresh.
1481       *
1482       * Injects attributes into container element.
1483       *
1484       * @since 4.3.0
1485       *
1486       * @see wp_nav_menu()
1487       *
1488       * @param string $nav_menu_content The HTML content for the navigation menu.
1489       * @param object $args             An object containing wp_nav_menu() arguments.
1490       * @return string Nav menu HTML with selective refresh attributes added if partial can be refreshed.
1491       */
1492  	public function filter_wp_nav_menu( $nav_menu_content, $args ) {
1493          if ( isset( $args->customize_preview_nav_menus_args['can_partial_refresh'] ) && $args->customize_preview_nav_menus_args['can_partial_refresh'] ) {
1494              $attributes       = sprintf( ' data-customize-partial-id="%s"', esc_attr( 'nav_menu_instance[' . $args->customize_preview_nav_menus_args['args_hmac'] . ']' ) );
1495              $attributes      .= ' data-customize-partial-type="nav_menu_instance"';
1496              $attributes      .= sprintf( ' data-customize-partial-placement-context="%s"', esc_attr( wp_json_encode( $args->customize_preview_nav_menus_args ) ) );
1497              $nav_menu_content = preg_replace( '#^(<\w+)#', '$1 ' . str_replace( '\\', '\\\\', $attributes ), $nav_menu_content, 1 );
1498          }
1499          return $nav_menu_content;
1500      }
1501  
1502      /**
1503       * Hashes (hmac) the nav menu arguments to ensure they are not tampered with when
1504       * submitted in the Ajax request.
1505       *
1506       * Note that the array is expected to be pre-sorted.
1507       *
1508       * @since 4.3.0
1509       *
1510       * @param array $args The arguments to hash.
1511       * @return string Hashed nav menu arguments.
1512       */
1513  	public function hash_nav_menu_args( $args ) {
1514          return wp_hash( serialize( $args ) );
1515      }
1516  
1517      /**
1518       * Enqueue scripts for the Customizer preview.
1519       *
1520       * @since 4.3.0
1521       */
1522  	public function customize_preview_enqueue_deps() {
1523          wp_enqueue_script( 'customize-preview-nav-menus' ); // Note that we have overridden this.
1524      }
1525  
1526      /**
1527       * Exports data from PHP to JS.
1528       *
1529       * @since 4.3.0
1530       */
1531  	public function export_preview_data() {
1532  
1533          // Why not wp_localize_script? Because we're not localizing, and it forces values into strings.
1534          $exports = array(
1535              'navMenuInstanceArgs' => $this->preview_nav_menu_instance_args,
1536          );
1537          printf( '<script>var _wpCustomizePreviewNavMenusExports = %s;</script>', wp_json_encode( $exports ) );
1538      }
1539  
1540      /**
1541       * Export any wp_nav_menu() calls during the rendering of any partials.
1542       *
1543       * @since 4.5.0
1544       *
1545       * @param array $response Response.
1546       * @return array Response.
1547       */
1548  	public function export_partial_rendered_nav_menu_instances( $response ) {
1549          $response['nav_menu_instance_args'] = $this->preview_nav_menu_instance_args;
1550          return $response;
1551      }
1552  
1553      /**
1554       * Render a specific menu via wp_nav_menu() using the supplied arguments.
1555       *
1556       * @since 4.3.0
1557       *
1558       * @see wp_nav_menu()
1559       *
1560       * @param WP_Customize_Partial $partial       Partial.
1561       * @param array                $nav_menu_args Nav menu args supplied as container context.
1562       * @return string|false
1563       */
1564  	public function render_nav_menu_partial( $partial, $nav_menu_args ) {
1565          unset( $partial );
1566  
1567          if ( ! isset( $nav_menu_args['args_hmac'] ) ) {
1568              // Error: missing_args_hmac.
1569              return false;
1570          }
1571  
1572          $nav_menu_args_hmac = $nav_menu_args['args_hmac'];
1573          unset( $nav_menu_args['args_hmac'] );
1574  
1575          ksort( $nav_menu_args );
1576          if ( ! hash_equals( $this->hash_nav_menu_args( $nav_menu_args ), $nav_menu_args_hmac ) ) {
1577              // Error: args_hmac_mismatch.
1578              return false;
1579          }
1580  
1581          ob_start();
1582          wp_nav_menu( $nav_menu_args );
1583          $content = ob_get_clean();
1584  
1585          return $content;
1586      }
1587  }


Generated : Thu Sep 24 08:20:02 2020 Cross-referenced by PHPXref