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 * When status is inserted, the placeholder post ID is stored in $previous_post_id.
136 * When status is error, the error is stored in $update_error.
140 * @var string updated|inserted|deleted|error
142 * @see WP_Customize_Nav_Menu_Item_Setting::update()
143 * @see WP_Customize_Nav_Menu_Item_Setting::amend_customize_save_response()
145 public $update_status;
148 * Any error object returned by wp_update_nav_menu_item() when setting is updated.
154 * @see WP_Customize_Nav_Menu_Item_Setting::update()
155 * @see WP_Customize_Nav_Menu_Item_Setting::amend_customize_save_response()
157 public $update_error;
162 * Any supplied $args override class property defaults.
167 * @param WP_Customize_Manager $manager Bootstrap Customizer instance.
168 * @param string $id An specific ID of the setting. Can be a
169 * theme mod or option name.
170 * @param array $args Optional. Setting arguments.
172 * @throws Exception If $id is not valid for this setting type.
174 public function __construct( WP_Customize_Manager $manager, $id, array $args = array() ) {
175 if ( empty( $manager->nav_menus ) ) {
176 throw new Exception( 'Expected WP_Customize_Manager::$nav_menus to be set.' );
179 if ( ! preg_match( self::ID_PATTERN, $id, $matches ) ) {
180 throw new Exception( "Illegal widget setting ID: $id" );
183 $this->post_id = intval( $matches['id'] );
184 add_action( 'wp_update_nav_menu_item', array( $this, 'flush_cached_value' ), 10, 2 );
186 parent::__construct( $manager, $id, $args );
188 // Ensure that an initially-supplied value is valid.
189 if ( isset( $this->value ) ) {
190 $this->populate_value();
191 foreach ( array_diff( array_keys( $this->default ), array_keys( $this->value ) ) as $missing ) {
192 throw new Exception( "Supplied nav_menu_item value missing property: $missing" );
199 * Clear the cached value when this nav menu item is updated.
204 * @param int $menu_id The term ID for the menu.
205 * @param int $menu_item_id The post ID for the menu item.
207 public function flush_cached_value( $menu_id, $menu_item_id ) {
209 if ( $menu_item_id === $this->post_id ) {
215 * Get the instance data for a given nav_menu_item setting.
220 * @see wp_setup_nav_menu_item()
222 * @return array|false Instance data array, or false if the item is marked for deletion.
224 public function value() {
225 if ( $this->is_previewed && $this->_previewed_blog_id === get_current_blog_id() ) {
226 $undefined = new stdClass(); // Symbol.
227 $post_value = $this->post_value( $undefined );
229 if ( $undefined === $post_value ) {
230 $value = $this->_original_value;
232 $value = $post_value;
234 } else if ( isset( $this->value ) ) {
235 $value = $this->value;
239 // Note that a ID of less than one indicates a nav_menu not yet inserted.
240 if ( $this->post_id > 0 ) {
241 $post = get_post( $this->post_id );
242 if ( $post && self::POST_TYPE === $post->post_type ) {
243 $value = (array) wp_setup_nav_menu_item( $post );
247 if ( ! is_array( $value ) ) {
248 $value = $this->default;
251 // Cache the value for future calls to avoid having to re-call wp_setup_nav_menu_item().
252 $this->value = $value;
253 $this->populate_value();
254 $value = $this->value;
261 * Ensure that the value is fully populated with the necessary properties.
263 * Translates some properties added by wp_setup_nav_menu_item() and removes others.
268 * @see WP_Customize_Nav_Menu_Item_Setting::value()
270 protected function populate_value() {
271 if ( ! is_array( $this->value ) ) {
275 if ( isset( $this->value['menu_order'] ) ) {
276 $this->value['position'] = $this->value['menu_order'];
277 unset( $this->value['menu_order'] );
279 if ( isset( $this->value['post_status'] ) ) {
280 $this->value['status'] = $this->value['post_status'];
281 unset( $this->value['post_status'] );
284 if ( ! isset( $this->value['original_title'] ) ) {
285 $original_title = '';
286 if ( 'post_type' === $this->value['type'] ) {
287 $original_title = get_the_title( $this->value['object_id'] );
288 } elseif ( 'taxonomy' === $this->value['type'] ) {
289 $original_title = get_term_field( 'name', $this->value['object_id'], $this->value['object'], 'raw' );
290 if ( is_wp_error( $original_title ) ) {
291 $original_title = '';
294 $this->value['original_title'] = html_entity_decode( $original_title, ENT_QUOTES, get_bloginfo( 'charset' ) );
297 if ( ! isset( $this->value['nav_menu_term_id'] ) && $this->post_id > 0 ) {
298 $menus = wp_get_post_terms( $this->post_id, WP_Customize_Nav_Menu_Setting::TAXONOMY, array(
301 if ( ! empty( $menus ) ) {
302 $this->value['nav_menu_term_id'] = array_shift( $menus );
304 $this->value['nav_menu_term_id'] = 0;
308 foreach ( array( 'object_id', 'menu_item_parent', 'nav_menu_term_id' ) as $key ) {
309 if ( ! is_int( $this->value[ $key ] ) ) {
310 $this->value[ $key ] = intval( $this->value[ $key ] );
313 foreach ( array( 'classes', 'xfn' ) as $key ) {
314 if ( is_array( $this->value[ $key ] ) ) {
315 $this->value[ $key ] = implode( ' ', $this->value[ $key ] );
319 if ( ! isset( $this->value['title'] ) ) {
320 $this->value['title'] = '';
323 if ( ! isset( $this->value['_invalid'] ) ) {
324 $this->value['_invalid'] = false;
325 $is_known_invalid = (
326 ( ( 'post_type' === $this->value['type'] || 'post_type_archive' === $this->value['type'] ) && ! post_type_exists( $this->value['object'] ) )
328 ( 'taxonomy' === $this->value['type'] && ! taxonomy_exists( $this->value['object'] ) )
330 if ( $is_known_invalid ) {
331 $this->value['_invalid'] = true;
335 // Remove remaining properties available on a setup nav_menu_item post object which aren't relevant to the setting value.
336 $irrelevant_properties = array(
347 'post_content_filtered',
361 foreach ( $irrelevant_properties as $property ) {
362 unset( $this->value[ $property ] );
367 * Handle previewing the setting.
370 * @since 4.4.0 Added boolean return value.
373 * @see WP_Customize_Manager::post_value()
375 * @return bool False if method short-circuited due to no-op.
377 public function preview() {
378 if ( $this->is_previewed ) {
382 $undefined = new stdClass();
383 $is_placeholder = ( $this->post_id < 0 );
384 $is_dirty = ( $undefined !== $this->post_value( $undefined ) );
385 if ( ! $is_placeholder && ! $is_dirty ) {
389 $this->is_previewed = true;
390 $this->_original_value = $this->value();
391 $this->original_nav_menu_term_id = $this->_original_value['nav_menu_term_id'];
392 $this->_previewed_blog_id = get_current_blog_id();
394 add_filter( 'wp_get_nav_menu_items', array( $this, 'filter_wp_get_nav_menu_items' ), 10, 3 );
396 $sort_callback = array( __CLASS__, 'sort_wp_get_nav_menu_items' );
397 if ( ! has_filter( 'wp_get_nav_menu_items', $sort_callback ) ) {
398 add_filter( 'wp_get_nav_menu_items', array( __CLASS__, 'sort_wp_get_nav_menu_items' ), 1000, 3 );
401 // @todo Add get_post_metadata filters for plugins to add their data.
407 * Filter the wp_get_nav_menu_items() result to supply the previewed menu items.
412 * @see wp_get_nav_menu_items()
414 * @param array $items An array of menu item post objects.
415 * @param object $menu The menu object.
416 * @param array $args An array of arguments used to retrieve menu item objects.
417 * @return array Array of menu items,
419 public function filter_wp_get_nav_menu_items( $items, $menu, $args ) {
420 $this_item = $this->value();
421 $current_nav_menu_term_id = $this_item['nav_menu_term_id'];
422 unset( $this_item['nav_menu_term_id'] );
425 $menu->term_id === $this->original_nav_menu_term_id
427 $menu->term_id === $current_nav_menu_term_id
429 if ( ! $should_filter ) {
433 // Handle deleted menu item, or menu item moved to another menu.
437 true === $this_item['_invalid']
440 $this->original_nav_menu_term_id === $menu->term_id
442 $current_nav_menu_term_id !== $this->original_nav_menu_term_id
445 if ( $should_remove ) {
446 $filtered_items = array();
447 foreach ( $items as $item ) {
448 if ( $item->db_id !== $this->post_id ) {
449 $filtered_items[] = $item;
452 return $filtered_items;
457 is_array( $this_item )
459 $current_nav_menu_term_id === $menu->term_id
461 if ( $should_update ) {
462 foreach ( $items as $item ) {
463 if ( $item->db_id === $this->post_id ) {
464 foreach ( get_object_vars( $this->value_as_wp_post_nav_menu_item() ) as $key => $value ) {
465 $item->$key = $value;
471 // Not found so we have to append it..
473 $items[] = $this->value_as_wp_post_nav_menu_item();
481 * Re-apply the tail logic also applied on $items by wp_get_nav_menu_items().
487 * @see wp_get_nav_menu_items()
489 * @param array $items An array of menu item post objects.
490 * @param object $menu The menu object.
491 * @param array $args An array of arguments used to retrieve menu item objects.
492 * @return array Array of menu items,
494 public static function sort_wp_get_nav_menu_items( $items, $menu, $args ) {
495 // @todo We should probably re-apply some constraints imposed by $args.
496 unset( $args['include'] );
498 // Remove invalid items only in front end.
499 if ( ! is_admin() ) {
500 $items = array_filter( $items, '_is_valid_nav_menu_item' );
503 if ( ARRAY_A === $args['output'] ) {
504 $GLOBALS['_menu_item_sort_prop'] = $args['output_key'];
505 usort( $items, '_sort_nav_menu_items' );
508 foreach ( $items as $k => $item ) {
509 $items[ $k ]->{$args['output_key']} = $i++;
517 * Get the value emulated into a WP_Post and set up as a nav_menu_item.
522 * @return WP_Post With wp_setup_nav_menu_item() applied.
524 public function value_as_wp_post_nav_menu_item() {
525 $item = (object) $this->value();
526 unset( $item->nav_menu_term_id );
528 $item->post_status = $item->status;
529 unset( $item->status );
531 $item->post_type = 'nav_menu_item';
532 $item->menu_order = $item->position;
533 unset( $item->position );
535 if ( $item->title ) {
536 $item->post_title = $item->title;
539 $item->ID = $this->post_id;
540 $item->db_id = $this->post_id;
541 $post = new WP_Post( (object) $item );
543 if ( empty( $post->post_author ) ) {
544 $post->post_author = get_current_user_id();
547 if ( ! isset( $post->type_label ) ) {
548 if ( 'post_type' === $post->type ) {
549 $object = get_post_type_object( $post->object );
551 $post->type_label = $object->labels->singular_name;
553 $post->type_label = $post->object;
555 } elseif ( 'taxonomy' == $post->type ) {
556 $object = get_taxonomy( $post->object );
558 $post->type_label = $object->labels->singular_name;
560 $post->type_label = $post->object;
563 $post->type_label = __( 'Custom Link' );
567 /** This filter is documented in wp-includes/nav-menu.php */
568 $post->attr_title = apply_filters( 'nav_menu_attr_title', $post->attr_title );
570 /** This filter is documented in wp-includes/nav-menu.php */
571 $post->description = apply_filters( 'nav_menu_description', wp_trim_words( $post->description, 200 ) );
579 * Note that parent::sanitize() erroneously does wp_unslash() on $value, but
580 * we remove that in this override.
585 * @param array $menu_item_value The value to sanitize.
586 * @return array|false|null Null if an input isn't valid. False if it is marked for deletion.
587 * Otherwise the sanitized value.
589 public function sanitize( $menu_item_value ) {
590 // Menu is marked for deletion.
591 if ( false === $menu_item_value ) {
592 return $menu_item_value;
596 if ( ! is_array( $menu_item_value ) ) {
603 'menu_item_parent' => 0,
613 'status' => 'publish',
614 'original_title' => '',
615 'nav_menu_term_id' => 0,
618 $menu_item_value = array_merge( $default, $menu_item_value );
619 $menu_item_value = wp_array_slice_assoc( $menu_item_value, array_keys( $default ) );
620 $menu_item_value['position'] = intval( $menu_item_value['position'] );
622 foreach ( array( 'object_id', 'menu_item_parent', 'nav_menu_term_id' ) as $key ) {
623 // Note we need to allow negative-integer IDs for previewed objects not inserted yet.
624 $menu_item_value[ $key ] = intval( $menu_item_value[ $key ] );
627 foreach ( array( 'type', 'object', 'target' ) as $key ) {
628 $menu_item_value[ $key ] = sanitize_key( $menu_item_value[ $key ] );
631 foreach ( array( 'xfn', 'classes' ) as $key ) {
632 $value = $menu_item_value[ $key ];
633 if ( ! is_array( $value ) ) {
634 $value = explode( ' ', $value );
636 $menu_item_value[ $key ] = implode( ' ', array_map( 'sanitize_html_class', $value ) );
639 $menu_item_value['original_title'] = sanitize_text_field( $menu_item_value['original_title'] );
641 // Apply the same filters as when calling wp_insert_post().
642 $menu_item_value['title'] = wp_unslash( apply_filters( 'title_save_pre', wp_slash( $menu_item_value['title'] ) ) );
643 $menu_item_value['attr_title'] = wp_unslash( apply_filters( 'excerpt_save_pre', wp_slash( $menu_item_value['attr_title'] ) ) );
644 $menu_item_value['description'] = wp_unslash( apply_filters( 'content_save_pre', wp_slash( $menu_item_value['description'] ) ) );
646 $menu_item_value['url'] = esc_url_raw( $menu_item_value['url'] );
647 if ( 'publish' !== $menu_item_value['status'] ) {
648 $menu_item_value['status'] = 'draft';
651 $menu_item_value['_invalid'] = (bool) $menu_item_value['_invalid'];
653 /** This filter is documented in wp-includes/class-wp-customize-setting.php */
654 return apply_filters( "customize_sanitize_{$this->id}", $menu_item_value, $this );
658 * Create/update the nav_menu_item post for this setting.
660 * Any created menu items will have their assigned post IDs exported to the client
661 * via the customize_save_response filter. Likewise, any errors will be exported
662 * to the client via the customize_save_response() filter.
664 * To delete a menu, the client can send false as the value.
669 * @see wp_update_nav_menu_item()
671 * @param array|false $value The menu item array to update. If false, then the menu item will be deleted
672 * entirely. See WP_Customize_Nav_Menu_Item_Setting::$default for what the value
676 protected function update( $value ) {
677 if ( $this->is_updated ) {
681 $this->is_updated = true;
682 $is_placeholder = ( $this->post_id < 0 );
683 $is_delete = ( false === $value );
685 // Update the cached value.
686 $this->value = $value;
688 add_filter( 'customize_save_response', array( $this, 'amend_customize_save_response' ) );
691 // If the current setting post is a placeholder, a delete request is a no-op.
692 if ( $is_placeholder ) {
693 $this->update_status = 'deleted';
695 $r = wp_delete_post( $this->post_id, true );
697 if ( false === $r ) {
698 $this->update_error = new WP_Error( 'delete_failure' );
699 $this->update_status = 'error';
701 $this->update_status = 'deleted';
703 // @todo send back the IDs for all associated nav menu items deleted, so these settings (and controls) can be removed from Customizer?
707 // Handle saving menu items for menus that are being newly-created.
708 if ( $value['nav_menu_term_id'] < 0 ) {
709 $nav_menu_setting_id = sprintf( 'nav_menu[%s]', $value['nav_menu_term_id'] );
710 $nav_menu_setting = $this->manager->get_setting( $nav_menu_setting_id );
712 if ( ! $nav_menu_setting || ! ( $nav_menu_setting instanceof WP_Customize_Nav_Menu_Setting ) ) {
713 $this->update_status = 'error';
714 $this->update_error = new WP_Error( 'unexpected_nav_menu_setting' );
718 if ( false === $nav_menu_setting->save() ) {
719 $this->update_status = 'error';
720 $this->update_error = new WP_Error( 'nav_menu_setting_failure' );
724 if ( $nav_menu_setting->previous_term_id !== intval( $value['nav_menu_term_id'] ) ) {
725 $this->update_status = 'error';
726 $this->update_error = new WP_Error( 'unexpected_previous_term_id' );
730 $value['nav_menu_term_id'] = $nav_menu_setting->term_id;
733 // Handle saving a nav menu item that is a child of a nav menu item being newly-created.
734 if ( $value['menu_item_parent'] < 0 ) {
735 $parent_nav_menu_item_setting_id = sprintf( 'nav_menu_item[%s]', $value['menu_item_parent'] );
736 $parent_nav_menu_item_setting = $this->manager->get_setting( $parent_nav_menu_item_setting_id );
738 if ( ! $parent_nav_menu_item_setting || ! ( $parent_nav_menu_item_setting instanceof WP_Customize_Nav_Menu_Item_Setting ) ) {
739 $this->update_status = 'error';
740 $this->update_error = new WP_Error( 'unexpected_nav_menu_item_setting' );
744 if ( false === $parent_nav_menu_item_setting->save() ) {
745 $this->update_status = 'error';
746 $this->update_error = new WP_Error( 'nav_menu_item_setting_failure' );
750 if ( $parent_nav_menu_item_setting->previous_post_id !== intval( $value['menu_item_parent'] ) ) {
751 $this->update_status = 'error';
752 $this->update_error = new WP_Error( 'unexpected_previous_post_id' );
756 $value['menu_item_parent'] = $parent_nav_menu_item_setting->post_id;
759 // Insert or update menu.
760 $menu_item_data = array(
761 'menu-item-object-id' => $value['object_id'],
762 'menu-item-object' => $value['object'],
763 'menu-item-parent-id' => $value['menu_item_parent'],
764 'menu-item-position' => $value['position'],
765 'menu-item-type' => $value['type'],
766 'menu-item-title' => $value['title'],
767 'menu-item-url' => $value['url'],
768 'menu-item-description' => $value['description'],
769 'menu-item-attr-title' => $value['attr_title'],
770 'menu-item-target' => $value['target'],
771 'menu-item-classes' => $value['classes'],
772 'menu-item-xfn' => $value['xfn'],
773 'menu-item-status' => $value['status'],
776 $r = wp_update_nav_menu_item(
777 $value['nav_menu_term_id'],
778 $is_placeholder ? 0 : $this->post_id,
779 wp_slash( $menu_item_data )
782 if ( is_wp_error( $r ) ) {
783 $this->update_status = 'error';
784 $this->update_error = $r;
786 if ( $is_placeholder ) {
787 $this->previous_post_id = $this->post_id;
789 $this->update_status = 'inserted';
791 $this->update_status = 'updated';
799 * Export data for the JS client.
804 * @see WP_Customize_Nav_Menu_Item_Setting::update()
806 * @param array $data Additional information passed back to the 'saved' event on `wp.customize`.
807 * @return array Save response data.
809 public function amend_customize_save_response( $data ) {
810 if ( ! isset( $data['nav_menu_item_updates'] ) ) {
811 $data['nav_menu_item_updates'] = array();
814 $data['nav_menu_item_updates'][] = array(
815 'post_id' => $this->post_id,
816 'previous_post_id' => $this->previous_post_id,
817 'error' => $this->update_error ? $this->update_error->get_error_code() : null,
818 'status' => $this->update_status,