This shows you the differences between two versions of the page.
Next revision | Previous revision | ||
programmieren:wordpress:rest_api_mit_statischer_klasse [2024/07/12 20:01] – created jgehrke | programmieren:wordpress:rest_api_mit_statischer_klasse [2024/12/13 11:12] (current) – jgehrke | ||
---|---|---|---|
Line 1: | Line 1: | ||
====== Eigener Wordpress Rest API Endpoint mit Static Class ====== | ====== Eigener Wordpress Rest API Endpoint mit Static Class ====== | ||
+ | |||
+ | Manchmal ist es nötig für AJAX Requests eine Custom Rest-Route zu erstellen ohne Plugin. Mit diesem Code Snippet kann man eine Route in WP registrieren und eine JSON Antwort senden. In diesem Beispiel wird eine Route als GET und als POST zur Verfügung gestellt. | ||
+ | |||
+ | Alle Daten, egal ob GET POST oder PUT etc werden im WP_REST_Request Objekt fest gehalten. Das ist wichtig. Denn $_POST & $_GET funktionieren __nicht__ im REST-API-Endpoint! | ||
+ | |||
+ | **Hinweis: | ||
<code php> | <code php> | ||
+ | <?php | ||
+ | namespace theme\wp_rest; | ||
+ | use WP_REST_Request; | ||
+ | |||
/ | / | ||
* REST API ENDPOINT | * REST API ENDPOINT | ||
Line 16: | Line 26: | ||
{ | { | ||
/* | /* | ||
- | GET / | + | POST|GET / |
*/ | */ | ||
public static $rest_namespace | public static $rest_namespace | ||
Line 56: | Line 66: | ||
* JSON umgewandelt. | * JSON umgewandelt. | ||
* | * | ||
- | * @return | + | * @return |
*/ | */ | ||
- | public static function rest_response( WP_REST_Request $request | + | public static function rest_response( WP_REST_Request $wp_request |
{ | { | ||
+ | $http_request_daten = $_REQUEST; // POST, GET, etc.. | ||
+ | |||
return [ | return [ | ||
' | ' | ||
- | 'request' => $request, | + | 'wp_request' => $wp_request, |
+ | ' | ||
]; | ]; | ||
} | } |