rest api - Access WP_REST_Server from within plugin namespace

admin2025-06-03  3

I am new to OOP and developing plugins. I have developed a plugin using the Plugin-Boilerplate with namespace. I expanded the boilerplate to include a REST folder and class so I could create custom routs/endpoints. It is working; however I cannot use the WP_REST_Server object. I get the following error: ..class-wp-rest-server.php does not exist.From my limited knowledge of oop my guess I it is not in my namespace. But how do I include/access it? My guess is there is a simple mechanism that is obvious to experienced OOPs. Thanks.

I am new to OOP and developing plugins. I have developed a plugin using the Plugin-Boilerplate with namespace. I expanded the boilerplate to include a REST folder and class so I could create custom routs/endpoints. It is working; however I cannot use the WP_REST_Server object. I get the following error: ..class-wp-rest-server.php does not exist.From my limited knowledge of oop my guess I it is not in my namespace. But how do I include/access it? My guess is there is a simple mechanism that is obvious to experienced OOPs. Thanks.

Share Improve this question asked Feb 1, 2019 at 14:47 dsjdsj 638 bronze badges 2
  • 1 Don't know if this is precisely the problem you're having, but generally if you're in a namespace and want to access something in the global namespace you prefix it with a backslash. i.e. throw new \Exception( ... – tmdesigned Commented Feb 1, 2019 at 17:00
  • I though I had tried that with no effect. Tried it again and it worked. – dsj Commented Feb 1, 2019 at 17:25
Add a comment  | 

1 Answer 1

Reset to default 4

WordPress (version 5.0) doesn't use namespaces for it's classes, so try to use the global one:

\WP_REST_Server

to avoid assuming it's in your custom namespace.

One of the reason for this is that WordPress supports PHP 5.2.4+ that doesn't support namespaces. The minimum is PHP 5.3.3+, if I remember correctly, to support it.

Later this year (2019) WordPress plans to bump the minimum required PHP version to 5.6 and then to 7 at the end of the year. So after that, WordPress namespaces could be possible, but I'm not aware of any such planned changes though :-)

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1748953051a315111.html

最新回复(0)