Custom Endpoints

Give your plugin its own home: register_rest_route, a namespace with a version, one route with two doors.

4 lessons16 interview questions

wp/v2 is core's. Your plugin needs its own home. Deactivate the plugin and its route answers 404 rest_no_route. Activate it and one function opens the door. In this module you build that door on the real 4WP FAQ /settings route.

CourseWordPress REST API Course ยท Module 2 of 9 ยท Stage 2 "Build your own"
Learnregister_rest_route, namespace and version, method constants, permission_callback on every route, rest_url()
HowReal code from 4WP FAQ and 4WP Weather, review answers from wordpress.org, interview questions after every lesson

Namespace. Version. Resource.

flowchart LR
  NS["forwp-faq"] --> V["v1"] --> RS["/settings"]
  RS -- "GET ยท READABLE" --> CV["can_view<br/>edit_posts"]
  RS -- "POST ยท CREATABLE" --> CM["can_manage<br/>manage_options"]
  classDef get fill:#ebf3fb,stroke:#61affe,color:#1e293b
  classDef post fill:#e8f6f0,stroke:#49cc90,color:#1e293b
  class CV get
  class CM post

One route, two doors: an Editor reads the settings, only an Administrator changes them.

Before โ†’ after

BeforeAfter Module 2
Routes under wp/v2 "because it works"own namespace forwp-faq/v1, versioned
No permission_callback โ€” a notice since WP 5.5a callback on every route; __return_true only on purpose
home_url( '/wp-json/โ€ฆ' ) in an OAuth callbackrest_url() works with plain permalinks too
One callback for read and writeREADABLE and CREATABLE with different capabilities

You'll be able to answer

  • Why should a plugin never register routes under wp/v2?
  • What happens if a route has no permission_callback?
  • Why use rest_url() instead of building /wp-json/ by hand?

Lessons in this module 4 lessons