02 DE August DE 2019
Desde la versión 4.7 WordPress integra una REST API y hoy les voy hablar sobre un caso peculiar sobre las rutas personalizadas.
Digamos que tenemos esta ruta personalizada en un plugin para usar un formulario de contacto
1<?php 2 3add_action('rest_api_init', function () { 4 register_rest_route('myplugin/v1', '/foo', array( 5 'methods' => 'POST', 6 'callback' => 'my_awesome_func', 7 )); 8}); 9 10function my_awesome_func(WP_REST_Request $request)11{12 // TODO13}
Y para enviar los datos usamos la vieja y confiable funcion AJAX y que es algo como esto:
1var dataValue = { "hello": "there" }; 2 3$.ajax({ 4 url: 'http://wordpress.local/wp-json/myplugin/v1/foo', 5 dataType: 'json', 6 type: 'post', 7 contentType: 'application/json', 8 data: JSON.stringify( dataValue ), 9 processData: false,10 success: function( res ){11 // TODO12 },13});
Como se obtiene la data que estamos enviando al backend para trabajar con ella?
De seguro pueden encontrar por ahí en internet alguien que les diga:
To get JSON data (or any raw input), use php://input. lo cual no esta del todo mal pero ya que estamos usando WordPress podemos aprovechar el objeto request.
La documentación dice que:
"By default, routes receive all arguments passed in from the request. These are merged into a single set of parameters, then added to the Request object, which is passed in as the first parameter to your endpoint."
Entonces, podemos usar:
1$param = $request['some_param']; 2 3// Or via the helper method: 4$param = $request->get_param( 'some_param' ); 5 6// You can get the combined, merged set of parameters: 7$parameters = $request->get_params(); 8 9// The individual sets of parameters are also available, if needed:10$parameters = $request->get_url_params();11$parameters = $request->get_query_params();12$parameters = $request->get_body_params();13$parameters = $request->get_json_params();14$parameters = $request->get_default_params();15 16// Uploads aren't merged in, but can be accessed separately:17$parameters = $request->get_file_params();
Y para nuestro ejemplo estaríamos usando $parameters = $request->get_json_params();
y accedemos a los parámetros de esta forma: $parameters['hello']
.
Espero que esto le sirva a alguien más.
Made with ♥️ & 🧉 in Montevideo, Uruguay.
[AC].dev is not affiliated with Laravel or Laravel LLC. Laravel is a Trademark of Taylor Otwell.
Code highlighting provided by Torchlight.
We use cookies!
Hi, this website uses essential cookies to ensure its proper operation and tracking cookies to understand how you interact with it.