Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use slug instead of id for ref in Navigation block #42809

Open
wants to merge 8 commits into
base: trunk
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/reference-guides/core-blocks.md
Original file line number Diff line number Diff line change
Expand Up @@ -393,7 +393,7 @@ A collection of blocks that allow visitors to get around your site. ([Source](ht
- **Name:** core/navigation
- **Category:** theme
- **Supports:** align (full, wide), inserter, spacing (blockGap, units), typography (fontSize, lineHeight), ~~html~~
- **Attributes:** __unstableLocation, backgroundColor, customBackgroundColor, customOverlayBackgroundColor, customOverlayTextColor, customTextColor, hasIcon, icon, maxNestingLevel, openSubmenusOnClick, overlayBackgroundColor, overlayMenu, overlayTextColor, ref, rgbBackgroundColor, rgbTextColor, showSubmenuIcon, templateLock, textColor
- **Attributes:** __unstableLocation, backgroundColor, customBackgroundColor, customOverlayBackgroundColor, customOverlayTextColor, customTextColor, hasIcon, icon, maxNestingLevel, openSubmenusOnClick, overlayBackgroundColor, overlayMenu, overlayTextColor, ref, rgbBackgroundColor, rgbTextColor, showSubmenuIcon, slug, templateLock, textColor

## Custom Link

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
<?php
/**
* REST API: Gutenberg_REST_Templates_Controller class
*
* @package Gutenberg
* @subpackage REST_API
*/

/**
* Base Templates REST API Controller.
*/
class Gutenberg_REST_Navigation_Controller extends WP_REST_Posts_Controller {

/**
* Registers the controllers routes.
*
* @return void
*/
public function register_routes() {

parent::register_routes();

// Lists a single nav item based on the given id or slug.
register_rest_route(
$this->namespace,
'/' . $this->rest_base . '/((?P<id>[\d]+)|(?P<slug>[\w\-]+))',
array(
'args' => array(
'slug' => array(
'description' => __( 'The slug identifier for a Navigation', 'gutenberg' ),
getdave marked this conversation as resolved.
Show resolved Hide resolved
'type' => 'string',
),
),
array(
'methods' => WP_REST_Server::READABLE,
'callback' => array( $this, 'get_item' ),
'permission_callback' => array( $this, 'get_item_permissions_check' ),
'args' => $this->get_endpoint_args_for_item_schema( WP_REST_Server::READABLE ),
),
array(
'methods' => WP_REST_Server::EDITABLE,
'callback' => array( $this, 'update_item' ),
'permission_callback' => array( $this, 'update_item_permissions_check' ),
'args' => $this->get_endpoint_args_for_item_schema( WP_REST_Server::EDITABLE ),
),
array(
'methods' => WP_REST_Server::DELETABLE,
'callback' => array( $this, 'delete_item' ),
'permission_callback' => array( $this, 'delete_item_permissions_check' ),
'args' => array(
'force' => array(
'type' => 'boolean',
'default' => false,
'description' => __( 'Whether to bypass Trash and force deletion.' ),
),
),
),
'allow_batch' => $this->allow_batch,
'schema' => array( $this, 'get_public_item_schema' ),
)
);
}

/**
* Overide WP_REST_Posts_Controller parent function to query for
* `wp_navigation` posts by slug (post_name) instead of ID.
*
* This is required to successfully process OPTIONS requests as with
* these the `rest_request_before_callbacks` method which is used to
* map slug to postId does not run which means `get_post` will not
* behave as expected.
*
* The function will continue to delegate to the parent implementation
* if the $id argument is ID-based, thereby ensuring backwards
* compatbility.
*
* It may be possible to remove this implemenation in future releases.
*
* See: https://github.com/WordPress/gutenberg/pull/43703.
*
* @param string $id the slug of the Navigation post.
* @return WP_Post|null
*/
protected function get_post( $id ) {

// Handle ID based $id param.
if ( is_numeric( $id ) ) {
return parent::get_post( $id );
}

// For string based $id the argument is a "slug".
// Lookup Post using `post_name` query.
$slug = $id;

$args = array(
'name' => $slug,
'post_type' => 'wp_navigation',
'nopaging' => true,
'posts_per_page' => '1',
'update_post_term_cache' => false,
'no_found_rows' => true,
);

// Query for the Navigation Post by slug (post_name).
$query = new WP_Query( $args );

if ( empty( $query->posts ) ) {
return new WP_Error(
'rest_post_not_found',
__( 'No navigation found.' ),
array( 'status' => 404 )
);
}

return $query->posts[0];
}
}
83 changes: 83 additions & 0 deletions lib/compat/wordpress-6.1/rest-api.php
Original file line number Diff line number Diff line change
Expand Up @@ -93,3 +93,86 @@ function gutenberg_register_has_archive_on_post_types_endpoint() {
);
}
add_action( 'rest_api_init', 'gutenberg_register_has_archive_on_post_types_endpoint' );

/**
* Use custom REST API Controller for Navigation Posts
*
* @param array $args the post type arguments.
* @return array the filtered post type arguments with the new REST Controller set.
*/
function gutenberg_update_navigation_rest_controller( $args, $post_type ) {
if ( in_array( $post_type, array( 'wp_navigation' ), true ) ) {
// Original set in
// https://github.com/WordPress/wordpress-develop/blob/6cbed78c94b9d8c6a9b4c8b472b88ee0cd56528c/src/wp-includes/post.php#L528.
$args['rest_controller_class'] = 'Gutenberg_REST_Navigation_Controller';
}
return $args;
}
add_filter( 'register_post_type_args', 'gutenberg_update_navigation_rest_controller', 10, 2 );

function gutenberg_transform_slug_to_post_id( $response, $handler, WP_REST_Request $request ) {

$route = rest_get_route_for_post_type_items( 'wp_navigation' );

// Ignore non-Navigation REST API requests.
if ( ! str_starts_with( $request->get_route(), $route ) ) {
return $response;
}

// Get the slug from the request **URL** (not the request body).
// PUT requests will have a param of `slug` in both the URL and (potentially)
// in the body. In all cases only the slug in the URL should be mapped to a
// postId in order that the correct post to be updated can be retrived.
// The `slug` within the body should be preserved "as is".
$slug = isset( $request->get_url_params()['slug'] ) ? $request->get_url_params()['slug'] : null;

// If no slug provided assume ID and continue as normal.
if ( empty( $slug ) ) {
return $response;
}

$args = array(
'name' => $slug, // query by slug
'post_type' => 'wp_navigation',
'nopaging' => true,
'posts_per_page' => '1',
'update_post_term_cache' => false,
'no_found_rows' => true,
);

// Query for the Navigation Post by slug (post_name).
$query = new WP_Query( $args );

if ( empty( $query->posts ) ) {
return new WP_Error(
'rest_post_not_found',
__( 'No navigation found.' ),
array( 'status' => 404 )
);
}

// Set the post ID based on the slug.
$request['id'] = $query->posts[0]->ID;

return $response;
}
add_filter( 'rest_request_before_callbacks', 'gutenberg_transform_slug_to_post_id', 10, 3 );

function gutenberg_update_navigation_rest_route_for_post( $route, WP_Post $post ) {

if ( $post->post_type !== 'wp_navigation' ) {
return $route;
}

getdave marked this conversation as resolved.
Show resolved Hide resolved
$post_type_route = rest_get_route_for_post_type_items( $post->post_type );

if ( ! $post_type_route ) {
return '';
}

// Replace Post ID in route with Post "Slug" (post_name).
return sprintf( '%s/%s', $post_type_route, $post->post_name );
}


add_filter( 'rest_route_for_post', 'gutenberg_update_navigation_rest_route_for_post', 10, 2 );
1 change: 1 addition & 0 deletions lib/load.php
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ function gutenberg_is_experiment_enabled( $name ) {
// WordPress 6.1 compat.
require_once __DIR__ . '/compat/wordpress-6.1/class-gutenberg-rest-block-patterns-controller.php';
require_once __DIR__ . '/compat/wordpress-6.1/class-gutenberg-rest-templates-controller.php';
require_once __DIR__ . '/compat/wordpress-6.1/class-gutenberg-rest-navigation-controller.php';
require_once __DIR__ . '/compat/wordpress-6.1/rest-api.php';

// Experimental.
Expand Down
3 changes: 3 additions & 0 deletions packages/block-library/src/navigation/block.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@
"ref": {
"type": "number"
},
"slug": {
"type": "string"
},
"textColor": {
"type": "string"
},
Expand Down
2 changes: 2 additions & 0 deletions packages/block-library/src/navigation/constants.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export const DEFAULT_ENTITY_KIND = 'root';
export const DEFAULT_ENTITY_TYPE = 'navigation';