Make WordPress Core

Opened 3 months ago

Last modified 11 days ago

#53656 new defect (bug)

Not possible to get a post type's REST API namespace if modified

Reported by: swissspidy Owned by:
Milestone: Future Release Priority: normal
Severity: normal Version: 4.7
Component: REST API Keywords: needs-patch
Focuses: Cc:


It's possible to supply a custom rest_controller_class to register_post_type(). A post type's controller class can be retrieved using WP_Post_Type::get_rest_controller(). Same goes for taxonomies & WP_Taxonomy.

Now, such a custom controller can potentially change the namespace and rest_base for the post type, like so:

class My_Controller extends WP_REST_Posts_Controller {
        public function __construct() {
                $this->namespace = 'foo/v1';

register_post_type('bar', array( 'rest_controller_class' => My_Controller::class ) );

However, there's now no way to get the post type's REST API base URL (wp-json/foo/v1/bar.

For example, /wp-json/wp/v2/types/bar will link to /wp-json/wp/v2/bar because the wp/v2 namespace is hardcoded in WP_REST_Post_Types_Controller`.

Is there a way to get a post type's updated namespace and use that in WP_REST_Post_Types_Controller and other places?

Hardcoding everything to wp/v2 seems a bit limiting.

Or is the namespace perhaps not intended to be modified like this?

Change History (3)

#1 @TimothyBlynJacobs
3 months ago

  • Milestone changed from Awaiting Review to Future Release
  • Version set to 4.7

This is part of the reasoning behind introducing the rest_get_route_for_post functions, https://make.wordpress.org/core/2020/07/22/rest-api-changes-in-wordpress-5-5/. We don't have a collection version of this, but I think we could introduce one.

#2 @desrosj
2 months ago

  • Keywords needs-patch added

#3 @swissspidy
11 days ago

@TimothyBlynJacobs even rest_get_route_for_post() has this same problem, as the wp/v2 namespace is hardcoded there. But at least there's a filter.

To fix this, WP_REST_Controller needs a getter to access $namespace and $rest_base. Then functions like rest_get_route_for_post() or a potential rest_get_route_for_post_type() could get the REST controller for the entity and get the route via those getters.

Note: See TracTickets for help on using tickets.