WordPress Rest API
REST API List Posts Endpoint
We can use this endpoint of the rest API to fetch posts in JSON format to be used as AJAX or some other feature.
https://example.com/wp-json/wp/v2/{post-type}In this, we can change the post-type parameter to fetch different post-type.
We can also send GET parameters to this to alter the response.
- page => Which page to fetch, for example 1,2,3 -> this will get us the data for the specified page.
- per_page => Number of items to show per page.
We can also get the information of the total number of records and total number of pages by getting the response headers
- X-WP-Total -> This will give us the total number of records
- X-WP-TotalPages -> This will give us the total number of pages.
We can also add custom data or fields to the REST API response, for that we need to create a function and hook it to rest_api_init
In the function, we must use
register_rest_field(
'{post-type}',
'{field_name}',
array(
'get_callback' => function( $post ) {
// callback function which should return data
},
)
);We can add field for different {post-type} and name the fields through {field_name}
in our get_callback we should declare a function which should return the value for the field.
