[ Index ]

PHP Cross Reference of WordPress

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          // Register each menu as a Customizer section, and add each menu item to each menu.
 763          foreach ( $menus as $menu ) {
 764              $menu_id = $menu->term_id;
 765  
 766              // Create a section for each menu.
 767              $section_id = 'nav_menu[' . $menu_id . ']';
 768              $this->manager->add_section(
 769                  new WP_Customize_Nav_Menu_Section(
 770                      $this->manager,
 771                      $section_id,
 772                      array(
 773                          'title'    => html_entity_decode( $menu->name, ENT_QUOTES, get_bloginfo( 'charset' ) ),
 774                          'priority' => 10,
 775                          'panel'    => 'nav_menus',
 776                      )
 777                  )
 778              );
 779  
 780              $nav_menu_setting_id = 'nav_menu[' . $menu_id . ']';
 781              $this->manager->add_setting(
 782                  new WP_Customize_Nav_Menu_Setting(
 783                      $this->manager,
 784                      $nav_menu_setting_id,
 785                      array(
 786                          'transport' => 'postMessage',
 787                      )
 788                  )
 789              );
 790  
 791              // Add the menu contents.
 792              $menu_items = (array) wp_get_nav_menu_items( $menu_id );
 793  
 794              foreach ( array_values( $menu_items ) as $i => $item ) {
 795  
 796                  // Create a setting for each menu item (which doesn't actually manage data, currently).
 797                  $menu_item_setting_id = 'nav_menu_item[' . $item->ID . ']';
 798  
 799                  $value = (array) $item;
 800                  if ( empty( $value['post_title'] ) ) {
 801                      $value['title'] = '';
 802                  }
 803  
 804                  $value['nav_menu_term_id'] = $menu_id;
 805                  $this->manager->add_setting(
 806                      new WP_Customize_Nav_Menu_Item_Setting(
 807                          $this->manager,
 808                          $menu_item_setting_id,
 809                          array(
 810                              'value'     => $value,
 811                              'transport' => 'postMessage',
 812                          )
 813                      )
 814                  );
 815  
 816                  // Create a control for each menu item.
 817                  $this->manager->add_control(
 818                      new WP_Customize_Nav_Menu_Item_Control(
 819                          $this->manager,
 820                          $menu_item_setting_id,
 821                          array(
 822                              'label'    => $item->title,
 823                              'section'  => $section_id,
 824                              'priority' => 10 + $i,
 825                          )
 826                      )
 827                  );
 828              }
 829  
 830              // Note: other controls inside of this section get added dynamically in JS via the MenuSection.ready() function.
 831          }
 832  
 833          // Add the add-new-menu section and controls.
 834          $this->manager->add_section(
 835              'add_menu',
 836              array(
 837                  'type'     => 'new_menu',
 838                  'title'    => __( 'New Menu' ),
 839                  'panel'    => 'nav_menus',
 840                  'priority' => 20,
 841              )
 842          );
 843  
 844          $this->manager->add_setting(
 845              new WP_Customize_Filter_Setting(
 846                  $this->manager,
 847                  'nav_menus_created_posts',
 848                  array(
 849                      'transport'         => 'postMessage',
 850                      'type'              => 'option', // To prevent theme prefix in changeset.
 851                      'default'           => array(),
 852                      'sanitize_callback' => array( $this, 'sanitize_nav_menus_created_posts' ),
 853                  )
 854              )
 855          );
 856      }
 857  
 858      /**
 859       * Get the base10 intval.
 860       *
 861       * This is used as a setting's sanitize_callback; we can't use just plain
 862       * intval because the second argument is not what intval() expects.
 863       *
 864       * @since 4.3.0
 865       *
 866       * @param mixed $value Number to convert.
 867       * @return int Integer.
 868       */
 869  	public function intval_base10( $value ) {
 870          return intval( $value, 10 );
 871      }
 872  
 873      /**
 874       * Return an array of all the available item types.
 875       *
 876       * @since 4.3.0
 877       * @since 4.7.0  Each array item now includes a `$type_label` in addition to `$title`, `$type`, and `$object`.
 878       *
 879       * @return array The available menu item types.
 880       */
 881  	public function available_item_types() {
 882          $item_types = array();
 883  
 884          $post_types = get_post_types( array( 'show_in_nav_menus' => true ), 'objects' );
 885          if ( $post_types ) {
 886              foreach ( $post_types as $slug => $post_type ) {
 887                  $item_types[] = array(
 888                      'title'      => $post_type->labels->name,
 889                      'type_label' => $post_type->labels->singular_name,
 890                      'type'       => 'post_type',
 891                      'object'     => $post_type->name,
 892                  );
 893              }
 894          }
 895  
 896          $taxonomies = get_taxonomies( array( 'show_in_nav_menus' => true ), 'objects' );
 897          if ( $taxonomies ) {
 898              foreach ( $taxonomies as $slug => $taxonomy ) {
 899                  if ( 'post_format' === $taxonomy && ! current_theme_supports( 'post-formats' ) ) {
 900                      continue;
 901                  }
 902                  $item_types[] = array(
 903                      'title'      => $taxonomy->labels->name,
 904                      'type_label' => $taxonomy->labels->singular_name,
 905                      'type'       => 'taxonomy',
 906                      'object'     => $taxonomy->name,
 907                  );
 908              }
 909          }
 910  
 911          /**
 912           * Filters the available menu item types.
 913           *
 914           * @since 4.3.0
 915           * @since 4.7.0  Each array item now includes a `$type_label` in addition to `$title`, `$type`, and `$object`.
 916           *
 917           * @param array $item_types Navigation menu item types.
 918           */
 919          $item_types = apply_filters( 'customize_nav_menu_available_item_types', $item_types );
 920  
 921          return $item_types;
 922      }
 923  
 924      /**
 925       * Add a new `auto-draft` post.
 926       *
 927       * @since 4.7.0
 928       *
 929       * @param array $postarr {
 930       *     Post array. Note that post_status is overridden to be `auto-draft`.
 931       *
 932       * @var string $post_title   Post title. Required.
 933       * @var string $post_type    Post type. Required.
 934       * @var string $post_name    Post name.
 935       * @var string $post_content Post content.
 936       * }
 937       * @return WP_Post|WP_Error Inserted auto-draft post object or error.
 938       */
 939  	public function insert_auto_draft_post( $postarr ) {
 940          if ( ! isset( $postarr['post_type'] ) ) {
 941              return new WP_Error( 'unknown_post_type', __( 'Invalid post type.' ) );
 942          }
 943          if ( empty( $postarr['post_title'] ) ) {
 944              return new WP_Error( 'empty_title', __( 'Empty title.' ) );
 945          }
 946          if ( ! empty( $postarr['post_status'] ) ) {
 947              return new WP_Error( 'status_forbidden', __( 'Status is forbidden.' ) );
 948          }
 949  
 950          /*
 951           * If the changeset is a draft, this will change to draft the next time the changeset
 952           * is updated; otherwise, auto-draft will persist in autosave revisions, until save.
 953           */
 954          $postarr['post_status'] = 'auto-draft';
 955  
 956          // Auto-drafts are allowed to have empty post_names, so it has to be explicitly set.
 957          if ( empty( $postarr['post_name'] ) ) {
 958              $postarr['post_name'] = sanitize_title( $postarr['post_title'] );
 959          }
 960          if ( ! isset( $postarr['meta_input'] ) ) {
 961              $postarr['meta_input'] = array();
 962          }
 963          $postarr['meta_input']['_customize_draft_post_name'] = $postarr['post_name'];
 964          $postarr['meta_input']['_customize_changeset_uuid']  = $this->manager->changeset_uuid();
 965          unset( $postarr['post_name'] );
 966  
 967          add_filter( 'wp_insert_post_empty_content', '__return_false', 1000 );
 968          $r = wp_insert_post( wp_slash( $postarr ), true );
 969          remove_filter( 'wp_insert_post_empty_content', '__return_false', 1000 );
 970  
 971          if ( is_wp_error( $r ) ) {
 972              return $r;
 973          } else {
 974              return get_post( $r );
 975          }
 976      }
 977  
 978      /**
 979       * Ajax handler for adding a new auto-draft post.
 980       *
 981       * @since 4.7.0
 982       */
 983  	public function ajax_insert_auto_draft_post() {
 984          if ( ! check_ajax_referer( 'customize-menus', 'customize-menus-nonce', false ) ) {
 985              wp_send_json_error( 'bad_nonce', 400 );
 986          }
 987  
 988          if ( ! current_user_can( 'customize' ) ) {
 989              wp_send_json_error( 'customize_not_allowed', 403 );
 990          }
 991  
 992          if ( empty( $_POST['params'] ) || ! is_array( $_POST['params'] ) ) {
 993              wp_send_json_error( 'missing_params', 400 );
 994          }
 995  
 996          $params         = wp_unslash( $_POST['params'] );
 997          $illegal_params = array_diff( array_keys( $params ), array( 'post_type', 'post_title' ) );
 998          if ( ! empty( $illegal_params ) ) {
 999              wp_send_json_error( 'illegal_params', 400 );
1000          }
1001  
1002          $params = array_merge(
1003              array(
1004                  'post_type'  => '',
1005                  'post_title' => '',
1006              ),
1007              $params
1008          );
1009  
1010          if ( empty( $params['post_type'] ) || ! post_type_exists( $params['post_type'] ) ) {
1011              status_header( 400 );
1012              wp_send_json_error( 'missing_post_type_param' );
1013          }
1014  
1015          $post_type_object = get_post_type_object( $params['post_type'] );
1016          if ( ! current_user_can( $post_type_object->cap->create_posts ) || ! current_user_can( $post_type_object->cap->publish_posts ) ) {
1017              status_header( 403 );
1018              wp_send_json_error( 'insufficient_post_permissions' );
1019          }
1020  
1021          $params['post_title'] = trim( $params['post_title'] );
1022          if ( '' === $params['post_title'] ) {
1023              status_header( 400 );
1024              wp_send_json_error( 'missing_post_title' );
1025          }
1026  
1027          $r = $this->insert_auto_draft_post( $params );
1028          if ( is_wp_error( $r ) ) {
1029              $error = $r;
1030              if ( ! empty( $post_type_object->labels->singular_name ) ) {
1031                  $singular_name = $post_type_object->labels->singular_name;
1032              } else {
1033                  $singular_name = __( 'Post' );
1034              }
1035  
1036              $data = array(
1037                  /* translators: 1: Post type name, 2: Error message. */
1038                  'message' => sprintf( __( '%1$s could not be created: %2$s' ), $singular_name, $error->get_error_message() ),
1039              );
1040              wp_send_json_error( $data );
1041          } else {
1042              $post = $r;
1043              $data = array(
1044                  'post_id' => $post->ID,
1045                  'url'     => get_permalink( $post->ID ),
1046              );
1047              wp_send_json_success( $data );
1048          }
1049      }
1050  
1051      /**
1052       * Print the JavaScript templates used to render Menu Customizer components.
1053       *
1054       * Templates are imported into the JS use wp.template.
1055       *
1056       * @since 4.3.0
1057       */
1058  	public function print_templates() {
1059          ?>
1060          <script type="text/html" id="tmpl-available-menu-item">
1061              <li id="menu-item-tpl-{{ data.id }}" class="menu-item-tpl" data-menu-item-id="{{ data.id }}">
1062                  <div class="menu-item-bar">
1063                      <div class="menu-item-handle">
1064                          <span class="item-type" aria-hidden="true">{{ data.type_label }}</span>
1065                          <span class="item-title" aria-hidden="true">
1066                              <span class="menu-item-title<# if ( ! data.title ) { #> no-title<# } #>">{{ data.title || wp.customize.Menus.data.l10n.untitled }}</span>
1067                          </span>
1068                          <button type="button" class="button-link item-add">
1069                              <span class="screen-reader-text">
1070                              <?php
1071                                  /* translators: 1: Title of a menu item, 2: Type of a menu item. */
1072                                  printf( __( 'Add to menu: %1$s (%2$s)' ), '{{ data.title || wp.customize.Menus.data.l10n.untitled }}', '{{ data.type_label }}' );
1073                              ?>
1074                              </span>
1075                          </button>
1076                      </div>
1077                  </div>
1078              </li>
1079          </script>
1080  
1081          <script type="text/html" id="tmpl-menu-item-reorder-nav">
1082              <div class="menu-item-reorder-nav">
1083                  <?php
1084                  printf(
1085                      '<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>',
1086                      __( 'Move up' ),
1087                      __( 'Move down' ),
1088                      __( 'Move one level up' ),
1089                      __( 'Move one level down' )
1090                  );
1091                  ?>
1092              </div>
1093          </script>
1094  
1095          <script type="text/html" id="tmpl-nav-menu-delete-button">
1096              <div class="menu-delete-item">
1097                  <button type="button" class="button-link button-link-delete">
1098                      <?php _e( 'Delete Menu' ); ?>
1099                  </button>
1100              </div>
1101          </script>
1102  
1103          <script type="text/html" id="tmpl-nav-menu-submit-new-button">
1104              <p id="customize-new-menu-submit-description"><?php _e( 'Click &#8220;Next&#8221; to start adding links to your new menu.' ); ?></p>
1105              <button id="customize-new-menu-submit" type="button" class="button" aria-describedby="customize-new-menu-submit-description"><?php _e( 'Next' ); ?></button>
1106          </script>
1107  
1108          <script type="text/html" id="tmpl-nav-menu-locations-header">
1109              <span class="customize-control-title customize-section-title-menu_locations-heading">{{ data.l10n.locationsTitle }}</span>
1110              <p class="customize-control-description customize-section-title-menu_locations-description">{{ data.l10n.locationsDescription }}</p>
1111          </script>
1112  
1113          <script type="text/html" id="tmpl-nav-menu-create-menu-section-title">
1114              <p class="add-new-menu-notice">
1115                  <?php _e( 'It doesn&#8217;t look like your site has any menus yet. Want to build one? Click the button to start.' ); ?>
1116              </p>
1117              <p class="add-new-menu-notice">
1118                  <?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.' ); ?>
1119              </p>
1120              <h3>
1121                  <button type="button" class="button customize-add-menu-button">
1122                      <?php _e( 'Create New Menu' ); ?>
1123                  </button>
1124              </h3>
1125          </script>
1126          <?php
1127      }
1128  
1129      /**
1130       * Print the HTML template used to render the add-menu-item frame.
1131       *
1132       * @since 4.3.0
1133       */
1134  	public function available_items_template() {
1135          ?>
1136          <div id="available-menu-items" class="accordion-container">
1137              <div class="customize-section-title">
1138                  <button type="button" class="customize-section-back" tabindex="-1">
1139                      <span class="screen-reader-text"><?php _e( 'Back' ); ?></span>
1140                  </button>
1141                  <h3>
1142                      <span class="customize-action">
1143                          <?php
1144                              /* translators: &#9656; is the unicode right-pointing triangle. %s: Section title in the Customizer. */
1145                              printf( __( 'Customizing &#9656; %s' ), esc_html( $this->manager->get_panel( 'nav_menus' )->title ) );
1146                          ?>
1147                      </span>
1148                      <?php _e( 'Add Menu Items' ); ?>
1149                  </h3>
1150              </div>
1151              <div id="available-menu-items-search" class="accordion-section cannot-expand">
1152                  <div class="accordion-section-title">
1153                      <label class="screen-reader-text" for="menu-items-search"><?php _e( 'Search Menu Items' ); ?></label>
1154                      <input type="text" id="menu-items-search" placeholder="<?php esc_attr_e( 'Search menu items&hellip;' ); ?>" aria-describedby="menu-items-search-desc" />
1155                      <p class="screen-reader-text" id="menu-items-search-desc"><?php _e( 'The search results will be updated as you type.' ); ?></p>
1156                      <span class="spinner"></span>
1157                  </div>
1158                  <div class="search-icon" aria-hidden="true"></div>
1159                  <button type="button" class="clear-results"><span class="screen-reader-text"><?php _e( 'Clear Results' ); ?></span></button>
1160                  <ul class="accordion-section-content available-menu-items-list" data-type="search"></ul>
1161              </div>
1162              <?php
1163  
1164              // Ensure the page post type comes first in the list.
1165              $item_types     = $this->available_item_types();
1166              $page_item_type = null;
1167              foreach ( $item_types as $i => $item_type ) {
1168                  if ( isset( $item_type['object'] ) && 'page' === $item_type['object'] ) {
1169                      $page_item_type = $item_type;
1170                      unset( $item_types[ $i ] );
1171                  }
1172              }
1173  
1174              $this->print_custom_links_available_menu_item();
1175              if ( $page_item_type ) {
1176                  $this->print_post_type_container( $page_item_type );
1177              }
1178              // Containers for per-post-type item browsing; items are added with JS.
1179              foreach ( $item_types as $item_type ) {
1180                  $this->print_post_type_container( $item_type );
1181              }
1182              ?>
1183          </div><!-- #available-menu-items -->
1184          <?php
1185      }
1186  
1187      /**
1188       * Print the markup for new menu items.
1189       *
1190       * To be used in the template #available-menu-items.
1191       *
1192       * @since 4.7.0
1193       *
1194       * @param array $available_item_type Menu item data to output, including title, type, and label.
1195       * @return void
1196       */
1197  	protected function print_post_type_container( $available_item_type ) {
1198          $id = sprintf( 'available-menu-items-%s-%s', $available_item_type['type'], $available_item_type['object'] );
1199          ?>
1200          <div id="<?php echo esc_attr( $id ); ?>" class="accordion-section">
1201              <h4 class="accordion-section-title" role="presentation">
1202                  <?php echo esc_html( $available_item_type['title'] ); ?>
1203                  <span class="spinner"></span>
1204                  <span class="no-items"><?php _e( 'No items' ); ?></span>
1205                  <button type="button" class="button-link" aria-expanded="false">
1206                      <span class="screen-reader-text">
1207                      <?php
1208                          /* translators: %s: Title of a section with menu items. */
1209                          printf( __( 'Toggle section: %s' ), esc_html( $available_item_type['title'] ) );
1210                      ?>
1211                          </span>
1212                      <span class="toggle-indicator" aria-hidden="true"></span>
1213                  </button>
1214              </h4>
1215              <div class="accordion-section-content">
1216                  <?php if ( 'post_type' === $available_item_type['type'] ) : ?>
1217                      <?php $post_type_obj = get_post_type_object( $available_item_type['object'] ); ?>
1218                      <?php if ( current_user_can( $post_type_obj->cap->create_posts ) && current_user_can( $post_type_obj->cap->publish_posts ) ) : ?>
1219                          <div class="new-content-item">
1220                              <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>
1221                              <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 ); ?>">
1222                              <button type="button" class="button add-content"><?php _e( 'Add' ); ?></button>
1223                          </div>
1224                      <?php endif; ?>
1225                  <?php endif; ?>
1226                  <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>
1227              </div>
1228          </div>
1229          <?php
1230      }
1231  
1232      /**
1233       * Print the markup for available menu item custom links.
1234       *
1235       * @since 4.7.0
1236       *
1237       * @return void
1238       */
1239  	protected function print_custom_links_available_menu_item() {
1240          ?>
1241          <div id="new-custom-menu-item" class="accordion-section">
1242              <h4 class="accordion-section-title" role="presentation">
1243                  <?php _e( 'Custom Links' ); ?>
1244                  <button type="button" class="button-link" aria-expanded="false">
1245                      <span class="screen-reader-text"><?php _e( 'Toggle section: Custom Links' ); ?></span>
1246                      <span class="toggle-indicator" aria-hidden="true"></span>
1247                  </button>
1248              </h4>
1249              <div class="accordion-section-content customlinkdiv">
1250                  <input type="hidden" value="custom" id="custom-menu-item-type" name="menu-item[-1][menu-item-type]" />
1251                  <p id="menu-item-url-wrap" class="wp-clearfix">
1252                      <label class="howto" for="custom-menu-item-url"><?php _e( 'URL' ); ?></label>
1253                      <input id="custom-menu-item-url" name="menu-item[-1][menu-item-url]" type="text" class="code menu-item-textbox" placeholder="https://">
1254                  </p>
1255                  <p id="menu-item-name-wrap" class="wp-clearfix">
1256                      <label class="howto" for="custom-menu-item-name"><?php _e( 'Link Text' ); ?></label>
1257                      <input id="custom-menu-item-name" name="menu-item[-1][menu-item-title]" type="text" class="regular-text menu-item-textbox">
1258                  </p>
1259                  <p class="button-controls">
1260                      <span class="add-to-menu">
1261                          <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">
1262                          <span class="spinner"></span>
1263                      </span>
1264                  </p>
1265              </div>
1266          </div>
1267          <?php
1268      }
1269  
1270      //
1271      // Start functionality specific to partial-refresh of menu changes in Customizer preview.
1272      //
1273  
1274      /**
1275       * Nav menu args used for each instance, keyed by the args HMAC.
1276       *
1277       * @since 4.3.0
1278       * @var array
1279       */
1280      public $preview_nav_menu_instance_args = array();
1281  
1282      /**
1283       * Filters arguments for dynamic nav_menu selective refresh partials.
1284       *
1285       * @since 4.5.0
1286       *
1287       * @param array|false $partial_args Partial args.
1288       * @param string      $partial_id   Partial ID.
1289       * @return array Partial args.
1290       */
1291  	public function customize_dynamic_partial_args( $partial_args, $partial_id ) {
1292  
1293          if ( preg_match( '/^nav_menu_instance\[[0-9a-f]{32}\]$/', $partial_id ) ) {
1294              if ( false === $partial_args ) {
1295                  $partial_args = array();
1296              }
1297              $partial_args = array_merge(
1298                  $partial_args,
1299                  array(
1300                      'type'                => 'nav_menu_instance',
1301                      'render_callback'     => array( $this, 'render_nav_menu_partial' ),
1302                      'container_inclusive' => true,
1303                      'settings'            => array(), // Empty because the nav menu instance may relate to a menu or a location.
1304                      'capability'          => 'edit_theme_options',
1305                  )
1306              );
1307          }
1308  
1309          return $partial_args;
1310      }
1311  
1312      /**
1313       * Add hooks for the Customizer preview.
1314       *
1315       * @since 4.3.0
1316       */
1317  	public function customize_preview_init() {
1318          add_action( 'wp_enqueue_scripts', array( $this, 'customize_preview_enqueue_deps' ) );
1319          add_filter( 'wp_nav_menu_args', array( $this, 'filter_wp_nav_menu_args' ), 1000 );
1320          add_filter( 'wp_nav_menu', array( $this, 'filter_wp_nav_menu' ), 10, 2 );
1321          add_filter( 'wp_footer', array( $this, 'export_preview_data' ), 1 );
1322          add_filter( 'customize_render_partials_response', array( $this, 'export_partial_rendered_nav_menu_instances' ) );
1323      }
1324  
1325      /**
1326       * Make the auto-draft status protected so that it can be queried.
1327       *
1328       * @since 4.7.0
1329       *
1330       * @global array $wp_post_statuses List of post statuses.
1331       */
1332  	public function make_auto_draft_status_previewable() {
1333          global $wp_post_statuses;
1334          $wp_post_statuses['auto-draft']->protected = true;
1335      }
1336  
1337      /**
1338       * Sanitize post IDs for posts created for nav menu items to be published.
1339       *
1340       * @since 4.7.0
1341       *
1342       * @param array $value Post IDs.
1343       * @return array Post IDs.
1344       */
1345  	public function sanitize_nav_menus_created_posts( $value ) {
1346          $post_ids = array();
1347          foreach ( wp_parse_id_list( $value ) as $post_id ) {
1348              if ( empty( $post_id ) ) {
1349                  continue;
1350              }
1351              $post = get_post( $post_id );
1352              if ( 'auto-draft' !== $post->post_status && 'draft' !== $post->post_status ) {
1353                  continue;
1354              }
1355              $post_type_obj = get_post_type_object( $post->post_type );
1356              if ( ! $post_type_obj ) {
1357                  continue;
1358              }
1359              if ( ! current_user_can( $post_type_obj->cap->publish_posts ) || ! current_user_can( 'edit_post', $post_id ) ) {
1360                  continue;
1361              }
1362              $post_ids[] = $post->ID;
1363          }
1364          return $post_ids;
1365      }
1366  
1367      /**
1368       * Publish the auto-draft posts that were created for nav menu items.
1369       *
1370       * The post IDs will have been sanitized by already by
1371       * `WP_Customize_Nav_Menu_Items::sanitize_nav_menus_created_posts()` to
1372       * remove any post IDs for which the user cannot publish or for which the
1373       * post is not an auto-draft.
1374       *
1375       * @since 4.7.0
1376       *
1377       * @param WP_Customize_Setting $setting Customizer setting object.
1378       */
1379  	public function save_nav_menus_created_posts( $setting ) {
1380          $post_ids = $setting->post_value();
1381          if ( ! empty( $post_ids ) ) {
1382              foreach ( $post_ids as $post_id ) {
1383  
1384                  // Prevent overriding the status that a user may have prematurely updated the post to.
1385                  $current_status = get_post_status( $post_id );
1386                  if ( 'auto-draft' !== $current_status && 'draft' !== $current_status ) {
1387                      continue;
1388                  }
1389  
1390                  $target_status = 'attachment' === get_post_type( $post_id ) ? 'inherit' : 'publish';
1391                  $args          = array(
1392                      'ID'          => $post_id,
1393                      'post_status' => $target_status,
1394                  );
1395                  $post_name     = get_post_meta( $post_id, '_customize_draft_post_name', true );
1396                  if ( $post_name ) {
1397                      $args['post_name'] = $post_name;
1398                  }
1399  
1400                  // Note that wp_publish_post() cannot be used because unique slugs need to be assigned.
1401                  wp_update_post( wp_slash( $args ) );
1402  
1403                  delete_post_meta( $post_id, '_customize_draft_post_name' );
1404              }
1405          }
1406      }
1407  
1408      /**
1409       * Keep track of the arguments that are being passed to wp_nav_menu().
1410       *
1411       * @since 4.3.0
1412       *
1413       * @see wp_nav_menu()
1414       * @see WP_Customize_Widgets::filter_dynamic_sidebar_params()
1415       *
1416       * @param array $args An array containing wp_nav_menu() arguments.
1417       * @return array Arguments.
1418       */
1419  	public function filter_wp_nav_menu_args( $args ) {
1420          /*
1421           * The following conditions determine whether or not this instance of
1422           * wp_nav_menu() can use selective refreshed. A wp_nav_menu() can be
1423           * selective refreshed if...
1424           */
1425          $can_partial_refresh = (
1426              // ...if wp_nav_menu() is directly echoing out the menu (and thus isn't manipulating the string after generated),
1427              ! empty( $args['echo'] )
1428              &&
1429              // ...and if the fallback_cb can be serialized to JSON, since it will be included in the placement context data,
1430              ( empty( $args['fallback_cb'] ) || is_string( $args['fallback_cb'] ) )
1431              &&
1432              // ...and if the walker can also be serialized to JSON, since it will be included in the placement context data as well,
1433              ( empty( $args['walker'] ) || is_string( $args['walker'] ) )
1434              // ...and if it has a theme location assigned or an assigned menu to display,
1435              && (
1436                  ! empty( $args['theme_location'] )
1437                  ||
1438                  ( ! empty( $args['menu'] ) && ( is_numeric( $args['menu'] ) || is_object( $args['menu'] ) ) )
1439              )
1440              &&
1441              // ...and if the nav menu would be rendered with a wrapper container element (upon which to attach data-* attributes).
1442              (
1443                  ! empty( $args['container'] )
1444                  ||
1445                  ( isset( $args['items_wrap'] ) && '<' === substr( $args['items_wrap'], 0, 1 ) )
1446              )
1447          );
1448          $args['can_partial_refresh'] = $can_partial_refresh;
1449  
1450          $exported_args = $args;
1451  
1452          // Empty out args which may not be JSON-serializable.
1453          if ( ! $can_partial_refresh ) {
1454              $exported_args['fallback_cb'] = '';
1455              $exported_args['walker']      = '';
1456          }
1457  
1458          /*
1459           * Replace object menu arg with a term_id menu arg, as this exports better
1460           * to JS and is easier to compare hashes.
1461           */
1462          if ( ! empty( $exported_args['menu'] ) && is_object( $exported_args['menu'] ) ) {
1463              $exported_args['menu'] = $exported_args['menu']->term_id;
1464          }
1465  
1466          ksort( $exported_args );
1467          $exported_args['args_hmac'] = $this->hash_nav_menu_args( $exported_args );
1468  
1469          $args['customize_preview_nav_menus_args']                            = $exported_args;
1470          $this->preview_nav_menu_instance_args[ $exported_args['args_hmac'] ] = $exported_args;
1471          return $args;
1472      }
1473  
1474      /**
1475       * Prepares wp_nav_menu() calls for partial refresh.
1476       *
1477       * Injects attributes into container element.
1478       *
1479       * @since 4.3.0
1480       *
1481       * @see wp_nav_menu()
1482       *
1483       * @param string $nav_menu_content The HTML content for the navigation menu.
1484       * @param object $args             An object containing wp_nav_menu() arguments.
1485       * @return string Nav menu HTML with selective refresh attributes added if partial can be refreshed.
1486       */
1487  	public function filter_wp_nav_menu( $nav_menu_content, $args ) {
1488          if ( isset( $args->customize_preview_nav_menus_args['can_partial_refresh'] ) && $args->customize_preview_nav_menus_args['can_partial_refresh'] ) {
1489              $attributes       = sprintf( ' data-customize-partial-id="%s"', esc_attr( 'nav_menu_instance[' . $args->customize_preview_nav_menus_args['args_hmac'] . ']' ) );
1490              $attributes      .= ' data-customize-partial-type="nav_menu_instance"';
1491              $attributes      .= sprintf( ' data-customize-partial-placement-context="%s"', esc_attr( wp_json_encode( $args->customize_preview_nav_menus_args ) ) );
1492              $nav_menu_content = preg_replace( '#^(<\w+)#', '$1 ' . str_replace( '\\', '\\\\', $attributes ), $nav_menu_content, 1 );
1493          }
1494          return $nav_menu_content;
1495      }
1496  
1497      /**
1498       * Hashes (hmac) the nav menu arguments to ensure they are not tampered with when
1499       * submitted in the Ajax request.
1500       *
1501       * Note that the array is expected to be pre-sorted.
1502       *
1503       * @since 4.3.0
1504       *
1505       * @param array $args The arguments to hash.
1506       * @return string Hashed nav menu arguments.
1507       */
1508  	public function hash_nav_menu_args( $args ) {
1509          return wp_hash( serialize( $args ) );
1510      }
1511  
1512      /**
1513       * Enqueue scripts for the Customizer preview.
1514       *
1515       * @since 4.3.0
1516       */
1517  	public function customize_preview_enqueue_deps() {
1518          wp_enqueue_script( 'customize-preview-nav-menus' ); // Note that we have overridden this.
1519      }
1520  
1521      /**
1522       * Exports data from PHP to JS.
1523       *
1524       * @since 4.3.0
1525       */
1526  	public function export_preview_data() {
1527  
1528          // Why not wp_localize_script? Because we're not localizing, and it forces values into strings.
1529          $exports = array(
1530              'navMenuInstanceArgs' => $this->preview_nav_menu_instance_args,
1531          );
1532          printf( '<script>var _wpCustomizePreviewNavMenusExports = %s;</script>', wp_json_encode( $exports ) );
1533      }
1534  
1535      /**
1536       * Export any wp_nav_menu() calls during the rendering of any partials.
1537       *
1538       * @since 4.5.0
1539       *
1540       * @param array $response Response.
1541       * @return array Response.
1542       */
1543  	public function export_partial_rendered_nav_menu_instances( $response ) {
1544          $response['nav_menu_instance_args'] = $this->preview_nav_menu_instance_args;
1545          return $response;
1546      }
1547  
1548      /**
1549       * Render a specific menu via wp_nav_menu() using the supplied arguments.
1550       *
1551       * @since 4.3.0
1552       *
1553       * @see wp_nav_menu()
1554       *
1555       * @param WP_Customize_Partial $partial       Partial.
1556       * @param array                $nav_menu_args Nav menu args supplied as container context.
1557       * @return string|false
1558       */
1559  	public function render_nav_menu_partial( $partial, $nav_menu_args ) {
1560          unset( $partial );
1561  
1562          if ( ! isset( $nav_menu_args['args_hmac'] ) ) {
1563              // Error: missing_args_hmac.
1564              return false;
1565          }
1566  
1567          $nav_menu_args_hmac = $nav_menu_args['args_hmac'];
1568          unset( $nav_menu_args['args_hmac'] );
1569  
1570          ksort( $nav_menu_args );
1571          if ( ! hash_equals( $this->hash_nav_menu_args( $nav_menu_args ), $nav_menu_args_hmac ) ) {
1572              // Error: args_hmac_mismatch.
1573              return false;
1574          }
1575  
1576          ob_start();
1577          wp_nav_menu( $nav_menu_args );
1578          $content = ob_get_clean();
1579  
1580          return $content;
1581      }
1582  }


Generated: Thu Jul 2 01:00:04 2020 Cross-referenced by PHPXref 0.7.1