3 * Customize API: WP_Customize_Nav_Menu_Item_Setting class
6 * @subpackage Customize
11 * Customize Setting to represent a nav_menu.
13 * Subclass of WP_Customize_Setting to represent a nav_menu taxonomy term, and
14 * the IDs for the nav_menu_items associated with the nav menu.
18 * @see WP_Customize_Setting
20 class WP_Customize_Nav_Menu_Item_Setting extends WP_Customize_Setting {
22 const ID_PATTERN = '/^nav_menu_item\[(?P<id>-?\d+)\]$/';
24 const POST_TYPE = 'nav_menu_item';
26 const TYPE = 'nav_menu_item';
35 public $type = self::TYPE;
38 * Default setting value.
44 * @see wp_setup_nav_menu_item()
46 public $default = array(
47 // The $menu_item_data for wp_update_nav_menu_item().
49 'object' => '', // Taxonomy name.
50 'menu_item_parent' => 0, // A.K.A. menu-item-parent-id; note that post_parent is different, and not included.
51 'position' => 0, // A.K.A. menu_order.
52 'type' => 'custom', // Note that type_label is not included here.
60 'status' => 'publish',
61 'original_title' => '',
62 'nav_menu_term_id' => 0, // This will be supplied as the $menu_id arg for wp_update_nav_menu_item().
70 * @since 4.5.0 Default changed to 'refresh'
74 public $transport = 'refresh';
77 * The post ID represented by this setting instance. This is the db_id.
79 * A negative value represents a placeholder ID for a new menu not yet saved.
88 * Storage of pre-setup menu item to prevent wasted calls to wp_setup_nav_menu_item().
97 * Previous (placeholder) post ID used before creating a new menu item.
99 * This value will be exported to JS via the customize_save_response filter
100 * so that JavaScript can update the settings to refer to the newly-assigned
101 * post ID. This value is always negative to indicate it does not refer to
108 * @see WP_Customize_Nav_Menu_Item_Setting::update()
109 * @see WP_Customize_Nav_Menu_Item_Setting::amend_customize_save_response()
111 public $previous_post_id;
114 * When previewing or updating a menu item, this stores the previous nav_menu_term_id
115 * which ensures that we can apply the proper filters.
121 public $original_nav_menu_term_id;
124 * Whether or not update() was called.
130 protected $is_updated = false;
133 * Status for calling the update method, used in customize_save_response filter.
135 * See {@see 'customize_save_response'}.
137 * When status is inserted, the placeholder post ID is stored in $previous_post_id.
138 * When status is error, the error is stored in $update_error.
142 * @var string updated|inserted|deleted|error
144 * @see WP_Customize_Nav_Menu_Item_Setting::update()
145 * @see WP_Customize_Nav_Menu_Item_Setting::amend_customize_save_response()
147 public $update_status;
150 * Any error object returned by wp_update_nav_menu_item() when setting is updated.
156 * @see WP_Customize_Nav_Menu_Item_Setting::update()
157 * @see WP_Customize_Nav_Menu_Item_Setting::amend_customize_save_response()
159 public $update_error;
164 * Any supplied $args override class property defaults.
169 * @param WP_Customize_Manager $manager Bootstrap Customizer instance.
170 * @param string $id An specific ID of the setting. Can be a
171 * theme mod or option name.
172 * @param array $args Optional. Setting arguments.
174 * @throws Exception If $id is not valid for this setting type.
176 public function __construct( WP_Customize_Manager $manager, $id, array $args = array() ) {
177 if ( empty( $manager->nav_menus ) ) {
178 throw new Exception( 'Expected WP_Customize_Manager::$nav_menus to be set.' );
181 if ( ! preg_match( self::ID_PATTERN, $id, $matches ) ) {
182 throw new Exception( "Illegal widget setting ID: $id" );
185 $this->post_id = intval( $matches['id'] );
186 add_action( 'wp_update_nav_menu_item', array( $this, 'flush_cached_value' ), 10, 2 );
188 parent::__construct( $manager, $id, $args );
190 // Ensure that an initially-supplied value is valid.
191 if ( isset( $this->value ) ) {
192 $this->populate_value();
193 foreach ( array_diff( array_keys( $this->default ), array_keys( $this->value ) ) as $missing ) {
194 throw new Exception( "Supplied nav_menu_item value missing property: $missing" );
201 * Clear the cached value when this nav menu item is updated.
206 * @param int $menu_id The term ID for the menu.
207 * @param int $menu_item_id The post ID for the menu item.
209 public function flush_cached_value( $menu_id, $menu_item_id ) {
211 if ( $menu_item_id === $this->post_id ) {
217 * Get the instance data for a given nav_menu_item setting.
222 * @see wp_setup_nav_menu_item()
224 * @return array|false Instance data array, or false if the item is marked for deletion.
226 public function value() {
227 if ( $this->is_previewed && $this->_previewed_blog_id === get_current_blog_id() ) {
228 $undefined = new stdClass(); // Symbol.
229 $post_value = $this->post_value( $undefined );
231 if ( $undefined === $post_value ) {
232 $value = $this->_original_value;
234 $value = $post_value;
236 } else if ( isset( $this->value ) ) {
237 $value = $this->value;
241 // Note that a ID of less than one indicates a nav_menu not yet inserted.
242 if ( $this->post_id > 0 ) {
243 $post = get_post( $this->post_id );
244 if ( $post && self::POST_TYPE === $post->post_type ) {
245 $value = (array) wp_setup_nav_menu_item( $post );
249 if ( ! is_array( $value ) ) {
250 $value = $this->default;
253 // Cache the value for future calls to avoid having to re-call wp_setup_nav_menu_item().
254 $this->value = $value;
255 $this->populate_value();
256 $value = $this->value;
263 * Ensure that the value is fully populated with the necessary properties.
265 * Translates some properties added by wp_setup_nav_menu_item() and removes others.
270 * @see WP_Customize_Nav_Menu_Item_Setting::value()
272 protected function populate_value() {
273 if ( ! is_array( $this->value ) ) {
277 if ( isset( $this->value['menu_order'] ) ) {
278 $this->value['position'] = $this->value['menu_order'];
279 unset( $this->value['menu_order'] );
281 if ( isset( $this->value['post_status'] ) ) {
282 $this->value['status'] = $this->value['post_status'];
283 unset( $this->value['post_status'] );
286 if ( ! isset( $this->value['original_title'] ) ) {
287 $original_title = '';
288 if ( 'post_type' === $this->value['type'] ) {
289 $original_title = get_the_title( $this->value['object_id'] );
290 } elseif ( 'taxonomy' === $this->value['type'] ) {
291 $original_title = get_term_field( 'name', $this->value['object_id'], $this->value['object'], 'raw' );
292 if ( is_wp_error( $original_title ) ) {
293 $original_title = '';
296 $this->value['original_title'] = html_entity_decode( $original_title, ENT_QUOTES, get_bloginfo( 'charset' ) );
299 if ( ! isset( $this->value['nav_menu_term_id'] ) && $this->post_id > 0 ) {
300 $menus = wp_get_post_terms( $this->post_id, WP_Customize_Nav_Menu_Setting::TAXONOMY, array(
303 if ( ! empty( $menus ) ) {
304 $this->value['nav_menu_term_id'] = array_shift( $menus );
306 $this->value['nav_menu_term_id'] = 0;
310 foreach ( array( 'object_id', 'menu_item_parent', 'nav_menu_term_id' ) as $key ) {
311 if ( ! is_int( $this->value[ $key ] ) ) {
312 $this->value[ $key ] = intval( $this->value[ $key ] );
315 foreach ( array( 'classes', 'xfn' ) as $key ) {
316 if ( is_array( $this->value[ $key ] ) ) {
317 $this->value[ $key ] = implode( ' ', $this->value[ $key ] );
321 if ( ! isset( $this->value['title'] ) ) {
322 $this->value['title'] = '';
325 if ( ! isset( $this->value['_invalid'] ) ) {
326 $this->value['_invalid'] = false;
327 $is_known_invalid = (
328 ( ( 'post_type' === $this->value['type'] || 'post_type_archive' === $this->value['type'] ) && ! post_type_exists( $this->value['object'] ) )
330 ( 'taxonomy' === $this->value['type'] && ! taxonomy_exists( $this->value['object'] ) )
332 if ( $is_known_invalid ) {
333 $this->value['_invalid'] = true;
337 // Remove remaining properties available on a setup nav_menu_item post object which aren't relevant to the setting value.
338 $irrelevant_properties = array(
349 'post_content_filtered',
363 foreach ( $irrelevant_properties as $property ) {
364 unset( $this->value[ $property ] );
369 * Handle previewing the setting.
372 * @since 4.4.0 Added boolean return value.
375 * @see WP_Customize_Manager::post_value()
377 * @return bool False if method short-circuited due to no-op.
379 public function preview() {
380 if ( $this->is_previewed ) {
384 $undefined = new stdClass();
385 $is_placeholder = ( $this->post_id < 0 );
386 $is_dirty = ( $undefined !== $this->post_value( $undefined ) );
387 if ( ! $is_placeholder && ! $is_dirty ) {
391 $this->is_previewed = true;
392 $this->_original_value = $this->value();
393 $this->original_nav_menu_term_id = $this->_original_value['nav_menu_term_id'];
394 $this->_previewed_blog_id = get_current_blog_id();
396 add_filter( 'wp_get_nav_menu_items', array( $this, 'filter_wp_get_nav_menu_items' ), 10, 3 );
398 $sort_callback = array( __CLASS__, 'sort_wp_get_nav_menu_items' );
399 if ( ! has_filter( 'wp_get_nav_menu_items', $sort_callback ) ) {
400 add_filter( 'wp_get_nav_menu_items', array( __CLASS__, 'sort_wp_get_nav_menu_items' ), 1000, 3 );
403 // @todo Add get_post_metadata filters for plugins to add their data.
409 * Filters the wp_get_nav_menu_items() result to supply the previewed menu items.
414 * @see wp_get_nav_menu_items()
416 * @param array $items An array of menu item post objects.
417 * @param object $menu The menu object.
418 * @param array $args An array of arguments used to retrieve menu item objects.
419 * @return array Array of menu items,
421 public function filter_wp_get_nav_menu_items( $items, $menu, $args ) {
422 $this_item = $this->value();
423 $current_nav_menu_term_id = $this_item['nav_menu_term_id'];
424 unset( $this_item['nav_menu_term_id'] );
427 $menu->term_id === $this->original_nav_menu_term_id
429 $menu->term_id === $current_nav_menu_term_id
431 if ( ! $should_filter ) {
435 // Handle deleted menu item, or menu item moved to another menu.
439 true === $this_item['_invalid']
442 $this->original_nav_menu_term_id === $menu->term_id
444 $current_nav_menu_term_id !== $this->original_nav_menu_term_id
447 if ( $should_remove ) {
448 $filtered_items = array();
449 foreach ( $items as $item ) {
450 if ( $item->db_id !== $this->post_id ) {
451 $filtered_items[] = $item;
454 return $filtered_items;
459 is_array( $this_item )
461 $current_nav_menu_term_id === $menu->term_id
463 if ( $should_update ) {
464 foreach ( $items as $item ) {
465 if ( $item->db_id === $this->post_id ) {
466 foreach ( get_object_vars( $this->value_as_wp_post_nav_menu_item() ) as $key => $value ) {
467 $item->$key = $value;
473 // Not found so we have to append it..
475 $items[] = $this->value_as_wp_post_nav_menu_item();
483 * Re-apply the tail logic also applied on $items by wp_get_nav_menu_items().
489 * @see wp_get_nav_menu_items()
491 * @param array $items An array of menu item post objects.
492 * @param object $menu The menu object.
493 * @param array $args An array of arguments used to retrieve menu item objects.
494 * @return array Array of menu items,
496 public static function sort_wp_get_nav_menu_items( $items, $menu, $args ) {
497 // @todo We should probably re-apply some constraints imposed by $args.
498 unset( $args['include'] );
500 // Remove invalid items only in front end.
501 if ( ! is_admin() ) {
502 $items = array_filter( $items, '_is_valid_nav_menu_item' );
505 if ( ARRAY_A === $args['output'] ) {
506 $GLOBALS['_menu_item_sort_prop'] = $args['output_key'];
507 usort( $items, '_sort_nav_menu_items' );
510 foreach ( $items as $k => $item ) {
511 $items[ $k ]->{$args['output_key']} = $i++;
519 * Get the value emulated into a WP_Post and set up as a nav_menu_item.
524 * @return WP_Post With wp_setup_nav_menu_item() applied.
526 public function value_as_wp_post_nav_menu_item() {
527 $item = (object) $this->value();
528 unset( $item->nav_menu_term_id );
530 $item->post_status = $item->status;
531 unset( $item->status );
533 $item->post_type = 'nav_menu_item';
534 $item->menu_order = $item->position;
535 unset( $item->position );
537 if ( $item->title ) {
538 $item->post_title = $item->title;
541 $item->ID = $this->post_id;
542 $item->db_id = $this->post_id;
543 $post = new WP_Post( (object) $item );
545 if ( empty( $post->post_author ) ) {
546 $post->post_author = get_current_user_id();
549 if ( ! isset( $post->type_label ) ) {
550 if ( 'post_type' === $post->type ) {
551 $object = get_post_type_object( $post->object );
553 $post->type_label = $object->labels->singular_name;
555 $post->type_label = $post->object;
557 } elseif ( 'taxonomy' == $post->type ) {
558 $object = get_taxonomy( $post->object );
560 $post->type_label = $object->labels->singular_name;
562 $post->type_label = $post->object;
565 $post->type_label = __( 'Custom Link' );
569 /** This filter is documented in wp-includes/nav-menu.php */
570 $post->attr_title = apply_filters( 'nav_menu_attr_title', $post->attr_title );
572 /** This filter is documented in wp-includes/nav-menu.php */
573 $post->description = apply_filters( 'nav_menu_description', wp_trim_words( $post->description, 200 ) );
575 /** This filter is documented in wp-includes/nav-menu.php */
576 $post = apply_filters( 'wp_setup_nav_menu_item', $post );
584 * Note that parent::sanitize() erroneously does wp_unslash() on $value, but
585 * we remove that in this override.
590 * @param array $menu_item_value The value to sanitize.
591 * @return array|false|null Null if an input isn't valid. False if it is marked for deletion.
592 * Otherwise the sanitized value.
594 public function sanitize( $menu_item_value ) {
595 // Menu is marked for deletion.
596 if ( false === $menu_item_value ) {
597 return $menu_item_value;
601 if ( ! is_array( $menu_item_value ) ) {
608 'menu_item_parent' => 0,
618 'status' => 'publish',
619 'original_title' => '',
620 'nav_menu_term_id' => 0,
623 $menu_item_value = array_merge( $default, $menu_item_value );
624 $menu_item_value = wp_array_slice_assoc( $menu_item_value, array_keys( $default ) );
625 $menu_item_value['position'] = intval( $menu_item_value['position'] );
627 foreach ( array( 'object_id', 'menu_item_parent', 'nav_menu_term_id' ) as $key ) {
628 // Note we need to allow negative-integer IDs for previewed objects not inserted yet.
629 $menu_item_value[ $key ] = intval( $menu_item_value[ $key ] );
632 foreach ( array( 'type', 'object', 'target' ) as $key ) {
633 $menu_item_value[ $key ] = sanitize_key( $menu_item_value[ $key ] );
636 foreach ( array( 'xfn', 'classes' ) as $key ) {
637 $value = $menu_item_value[ $key ];
638 if ( ! is_array( $value ) ) {
639 $value = explode( ' ', $value );
641 $menu_item_value[ $key ] = implode( ' ', array_map( 'sanitize_html_class', $value ) );
644 $menu_item_value['original_title'] = sanitize_text_field( $menu_item_value['original_title'] );
646 // Apply the same filters as when calling wp_insert_post().
647 $menu_item_value['title'] = wp_unslash( apply_filters( 'title_save_pre', wp_slash( $menu_item_value['title'] ) ) );
648 $menu_item_value['attr_title'] = wp_unslash( apply_filters( 'excerpt_save_pre', wp_slash( $menu_item_value['attr_title'] ) ) );
649 $menu_item_value['description'] = wp_unslash( apply_filters( 'content_save_pre', wp_slash( $menu_item_value['description'] ) ) );
651 $menu_item_value['url'] = esc_url_raw( $menu_item_value['url'] );
652 if ( 'publish' !== $menu_item_value['status'] ) {
653 $menu_item_value['status'] = 'draft';
656 $menu_item_value['_invalid'] = (bool) $menu_item_value['_invalid'];
658 /** This filter is documented in wp-includes/class-wp-customize-setting.php */
659 return apply_filters( "customize_sanitize_{$this->id}", $menu_item_value, $this );
663 * Creates/updates the nav_menu_item post for this setting.
665 * Any created menu items will have their assigned post IDs exported to the client
666 * via the {@see 'customize_save_response'} filter. Likewise, any errors will be
667 * exported to the client via the customize_save_response() filter.
669 * To delete a menu, the client can send false as the value.
674 * @see wp_update_nav_menu_item()
676 * @param array|false $value The menu item array to update. If false, then the menu item will be deleted
677 * entirely. See WP_Customize_Nav_Menu_Item_Setting::$default for what the value
681 protected function update( $value ) {
682 if ( $this->is_updated ) {
686 $this->is_updated = true;
687 $is_placeholder = ( $this->post_id < 0 );
688 $is_delete = ( false === $value );
690 // Update the cached value.
691 $this->value = $value;
693 add_filter( 'customize_save_response', array( $this, 'amend_customize_save_response' ) );
696 // If the current setting post is a placeholder, a delete request is a no-op.
697 if ( $is_placeholder ) {
698 $this->update_status = 'deleted';
700 $r = wp_delete_post( $this->post_id, true );
702 if ( false === $r ) {
703 $this->update_error = new WP_Error( 'delete_failure' );
704 $this->update_status = 'error';
706 $this->update_status = 'deleted';
708 // @todo send back the IDs for all associated nav menu items deleted, so these settings (and controls) can be removed from Customizer?
712 // Handle saving menu items for menus that are being newly-created.
713 if ( $value['nav_menu_term_id'] < 0 ) {
714 $nav_menu_setting_id = sprintf( 'nav_menu[%s]', $value['nav_menu_term_id'] );
715 $nav_menu_setting = $this->manager->get_setting( $nav_menu_setting_id );
717 if ( ! $nav_menu_setting || ! ( $nav_menu_setting instanceof WP_Customize_Nav_Menu_Setting ) ) {
718 $this->update_status = 'error';
719 $this->update_error = new WP_Error( 'unexpected_nav_menu_setting' );
723 if ( false === $nav_menu_setting->save() ) {
724 $this->update_status = 'error';
725 $this->update_error = new WP_Error( 'nav_menu_setting_failure' );
729 if ( $nav_menu_setting->previous_term_id !== intval( $value['nav_menu_term_id'] ) ) {
730 $this->update_status = 'error';
731 $this->update_error = new WP_Error( 'unexpected_previous_term_id' );
735 $value['nav_menu_term_id'] = $nav_menu_setting->term_id;
738 // Handle saving a nav menu item that is a child of a nav menu item being newly-created.
739 if ( $value['menu_item_parent'] < 0 ) {
740 $parent_nav_menu_item_setting_id = sprintf( 'nav_menu_item[%s]', $value['menu_item_parent'] );
741 $parent_nav_menu_item_setting = $this->manager->get_setting( $parent_nav_menu_item_setting_id );
743 if ( ! $parent_nav_menu_item_setting || ! ( $parent_nav_menu_item_setting instanceof WP_Customize_Nav_Menu_Item_Setting ) ) {
744 $this->update_status = 'error';
745 $this->update_error = new WP_Error( 'unexpected_nav_menu_item_setting' );
749 if ( false === $parent_nav_menu_item_setting->save() ) {
750 $this->update_status = 'error';
751 $this->update_error = new WP_Error( 'nav_menu_item_setting_failure' );
755 if ( $parent_nav_menu_item_setting->previous_post_id !== intval( $value['menu_item_parent'] ) ) {
756 $this->update_status = 'error';
757 $this->update_error = new WP_Error( 'unexpected_previous_post_id' );
761 $value['menu_item_parent'] = $parent_nav_menu_item_setting->post_id;
764 // Insert or update menu.
765 $menu_item_data = array(
766 'menu-item-object-id' => $value['object_id'],
767 'menu-item-object' => $value['object'],
768 'menu-item-parent-id' => $value['menu_item_parent'],
769 'menu-item-position' => $value['position'],
770 'menu-item-type' => $value['type'],
771 'menu-item-title' => $value['title'],
772 'menu-item-url' => $value['url'],
773 'menu-item-description' => $value['description'],
774 'menu-item-attr-title' => $value['attr_title'],
775 'menu-item-target' => $value['target'],
776 'menu-item-classes' => $value['classes'],
777 'menu-item-xfn' => $value['xfn'],
778 'menu-item-status' => $value['status'],
781 $r = wp_update_nav_menu_item(
782 $value['nav_menu_term_id'],
783 $is_placeholder ? 0 : $this->post_id,
784 wp_slash( $menu_item_data )
787 if ( is_wp_error( $r ) ) {
788 $this->update_status = 'error';
789 $this->update_error = $r;
791 if ( $is_placeholder ) {
792 $this->previous_post_id = $this->post_id;
794 $this->update_status = 'inserted';
796 $this->update_status = 'updated';
804 * Export data for the JS client.
809 * @see WP_Customize_Nav_Menu_Item_Setting::update()
811 * @param array $data Additional information passed back to the 'saved' event on `wp.customize`.
812 * @return array Save response data.
814 public function amend_customize_save_response( $data ) {
815 if ( ! isset( $data['nav_menu_item_updates'] ) ) {
816 $data['nav_menu_item_updates'] = array();
819 $data['nav_menu_item_updates'][] = array(
820 'post_id' => $this->post_id,
821 'previous_post_id' => $this->previous_post_id,
822 'error' => $this->update_error ? $this->update_error->get_error_code() : null,
823 'status' => $this->update_status,