WP_REST_Menus_Controller::handle_locations() WordPress Method

The WP_REST_Menus_Controller::handle_locations() method is responsible for handling menu locations when a menu is created or updated via the REST API. This method ensures that the correct menu locations are set for the menu, based on the location IDs provided in the request. If any invalid location IDs are provided, an error will be returned.

WP_REST_Menus_Controller::handle_locations( int $menu_id, WP_REST_Request $request ) #

Updates the menu’s locations from a REST request.


Parameters

$menu_id

(int)(Required)The menu id to update.

$request

(WP_REST_Request)(Required)Full details about the request.


Top ↑

Return

(true|WP_Error) True on success, a WP_Error on an error updating any of the locations.


Top ↑

Source

File: wp-includes/rest-api/endpoints/class-wp-rest-menus-controller.php

	protected function handle_locations( $menu_id, $request ) {
		if ( ! isset( $request['locations'] ) ) {
			return true;
		}

		$menu_locations = get_registered_nav_menus();
		$menu_locations = array_keys( $menu_locations );
		$new_locations  = array();
		foreach ( $request['locations'] as $location ) {
			if ( ! in_array( $location, $menu_locations, true ) ) {
				return new WP_Error(
					'rest_invalid_menu_location',
					__( 'Invalid menu location.' ),
					array(
						'status'   => 400,
						'location' => $location,
					)
				);
			}
			$new_locations[ $location ] = $menu_id;
		}
		$assigned_menu = get_nav_menu_locations();
		foreach ( $assigned_menu as $location => $term_id ) {
			if ( $term_id === $menu_id ) {
				unset( $assigned_menu[ $location ] );
			}
		}
		$new_assignments = array_merge( $assigned_menu, $new_locations );
		set_theme_mod( 'nav_menu_locations', $new_assignments );

		return true;
	}


Top ↑

Changelog

Changelog
VersionDescription
5.9.0Introduced.

The content displayed on this page has been created in part by processing WordPress source code files which are made available under the GPLv2 (or a later version) license by theĀ Free Software Foundation. In addition to this, the content includes user-written examples and information. All material is subject to review and curation by the WPPaste.com community.