WP_Customize_Nav_Menu_Setting::filter_wp_get_nav_menus

Advertisement

Summery Summery

Filters the wp_get_nav_menus() result to ensure the inserted menu object is included, and the deleted one is removed.

Syntax Syntax

WP_Customize_Nav_Menu_Setting::filter_wp_get_nav_menus( WP_Term[] $menus, array $args )

Parameters Parameters

$menus

(WP_Term[]) (Required) An array of menu objects.

$args

(array) (Required) An array of arguments used to retrieve menu objects.

Return Return

(WP_Term[]) Array of menu objects.

Source Source

File: wp-includes/customize/class-wp-customize-nav-menu-setting.php

	 */
	public function filter_wp_get_nav_menus( $menus, $args ) {
		if ( get_current_blog_id() !== $this->_previewed_blog_id ) {
			return $menus;
		}

		$setting_value = $this->value();
		$is_delete     = ( false === $setting_value );
		$index         = -1;

		// Find the existing menu item's position in the list.
		foreach ( $menus as $i => $menu ) {
			if ( (int) $this->term_id === (int) $menu->term_id || (int) $this->previous_term_id === (int) $menu->term_id ) {
				$index = $i;
				break;
			}
		}

		if ( $is_delete ) {
			// Handle deleted menu by removing it from the list.
			if ( -1 !== $index ) {
				array_splice( $menus, $index, 1 );
			}
		} else {
			// Handle menus being updated or inserted.
			$menu_obj = (object) array_merge(
				array(
					'term_id'          => $this->term_id,
					'term_taxonomy_id' => $this->term_id,
					'slug'             => sanitize_title( $setting_value['name'] ),
					'count'            => 0,
					'term_group'       => 0,
					'taxonomy'         => self::TAXONOMY,
					'filter'           => 'raw',
				),
				$setting_value
			);

			array_splice( $menus, $index, ( -1 === $index ? 0 : 1 ), array( $menu_obj ) );
		}

		// Make sure the menu objects get re-sorted after an update/insert.
		if ( ! $is_delete && ! empty( $args['orderby'] ) ) {
			$menus = wp_list_sort(
				$menus,
				array(
					$args['orderby'] => 'ASC',
				)
			);
		}
		// @todo Add support for $args['hide_empty'] === true.

		return $menus;

Advertisement

Changelog Changelog

Changelog
Version Description
4.3.0 Introduced.

See also See also

Advertisement

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.