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

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

Description

See also

Parameters

$menusWP_Term[]required
An array of menu objects.
$argsarrayrequired
An array of arguments used to retrieve menu objects.

Return

WP_Term[] Array of menu objects.

Source

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;
}

Changelog

VersionDescription
4.3.0Introduced.

User Contributed Notes

You must log in before being able to contribute a note or feedback.