Will set up a Rest API endpoint that will give all our posts
Reference guide: wordpress link
It will be a 2 step process
1. Register Route
add_action( 'rest_api_init', function() {
register_rest_route( 'myplugin/v1', '/author/(?P\d+)', array(
'methods' => 'GET',
'callback' => 'my_awesome_func',
) );
register_rest_route( 'myplugin/v1', '/allposts', array(
'methods' => 'GET',
'callback' => 'custom_get_all_posts',
) );
});
2. Get the route to pull all the posts
function custom_get_all_posts( $data ) {
$posts = get_posts( array(
) );
$args = array(
'numberposts' => 10
);
if ( empty( $posts ) ) {
return null;
}
return $posts;
}
Another example would be:
Having already an ID from the post, we can create a custom function which will get the data from that post.
function get_post_by_id( $data ) {
$args = array(
'p' => $data['id'],
'post_type' => 'post'
);
$post = new WP_Query($args);
return $post;
}
Leave A Comment?