Last active
September 19, 2019 13:06
-
-
Save filippo-quacquarelli/4c85f5ef5f2ea6171d15d2d46d5688d2 to your computer and use it in GitHub Desktop.
Tutorial for custom endpoint WordPress
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| // ecco l'action che fa funzionare la nostra chiamata | |
| add_action('rest_api_init', function () { | |
| // registriamo la nuova rotta, il primo parametro equivale al namespace, potrebbe essere myplugin/v1 ecc ecc | |
| // il secondo parametro equivale al percorso che vogliamo usare e le eventuali opzioni, | |
| // in questo esempio abbiamo aggiunto il parametro id, questo valore sarà poi disponibile nella funzione di callback | |
| register_rest_route( 'test/v1', '/post/(?P<id>\d+)', array( | |
| 'methods' => 'GET', // specifichiamo il metodo http | |
| // specifichiamo la funzione di callback dove andremo a specificare cosa ritornare | |
| 'callback' => 'api_get_post', | |
| )); | |
| }); | |
| // creiamo la nostra prima funzione che si occupa di ritornare il titolo di un post che andremo a specificare nell'endpoint | |
| function api_get_post( $data ) { | |
| // $data contiene dei parametri tra cui l'id che andremo a specificare nella richiesta | |
| $postID = intval($data['id']); | |
| // andiamo a recuperare i dati del post specificato con la funzione nativa get_post() | |
| $post = get_post($postID); | |
| // importante, se non troviamo il post specificato ritorniamo null | |
| if ( empty($post) ) return null; | |
| // creiamo la risposta della nostra chiamata, deve essere un array | |
| $post_data = array( $postID => $post->post_title ); | |
| // ritorniamo il nostro array non abbiamo bisogno di fare un json_encode è WordPress che se ne occupa per noi | |
| return $post_data; | |
| } | |
| // andiamo a vedere un metodo ancora più semplice, come tornare tutti i titoli dei post | |
| add_action( 'rest_api_init', function () { | |
| // tutto come prima a parte che non abbiamo più un'opzione specificata | |
| register_rest_route( 'test/v1', '/posts/', array( | |
| 'methods' => 'GET', | |
| 'callback' => 'api_get_posts', | |
| )); | |
| }); | |
| function api_get_posts( $data ) { | |
| $all_posts = array(); | |
| $posts = get_posts(); | |
| if ( empty($posts) ) return null; | |
| // più o meno tutto come prima a parte che dobbiamo ciclare tutti i post per andare ad inserire i dati che ci interessa esporre | |
| // all'interno di un'array, in questo caso abbiamo la chiave che corrisponde all'id del post e il valore al post_title | |
| foreach ( $posts as $post ) { | |
| $all_posts[$post->ID] = $post->post_title; | |
| } | |
| return $all_posts; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment