I want to create a cross-platform app using rest APIs for the website (zoetalentsolutions.com). The website is in WordPress and has custom post-types, fields & custom queries.
This app will not have any user auth.
What I want is to get custom post-type (in my case: courses) in REST & need to run a custom query (custom meta-query).
So I need a little guidance:
- How to create REST API for the custom post type
- How to create end-point for a custom query.
Any help would be appreciated around this.
I’m not expecting a thorough and but a details steps with brief would be helpful.
I believe the second question needs to be asked as a separate but I only need a brief idea of it.
Thank you.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Answering questions myself. I hope this will help some folks.
1.How to create REST API for the custom post type
If you’re creating a new custom post type then make sure this option is set to true in your arguments array:
show_in_rest' => true,
If your custom post is from a theme or plugin and you want to enable rest-api for it, then add this code into your child-theme functions.php
/**
* Add REST API support to an already registered post type.
*/
add_filter( 'register_post_type_args', 'my_post_type_args', 10, 2 );
function my_post_type_args( $args, $post_type ) {
if ( 'course' === $post_type ) {
$args['show_in_rest'] = true;
// Optionally customize the rest_base or rest_controller_class
$args['rest_base'] = 'course';
$args['rest_controller_class'] = 'WP_REST_Posts_Controller';
}
return $args;
}
2.How to create an end-point for a custom query.
Let’s say you want to run some wp-query and needs to send a custom parameter & access that query from rest-API
add_action('rest_api_init', function () {
register_rest_route( 'namespace/v2', 'events/(?P<id>d+)',array(
'methods' => 'GET',
'callback' => 'get_events_from_id'
));
});
//Now create a function to return your custom query results
function get_events_from_id($request){
$id = $request['id'];
// Custom WP query query
$args_query = array(
'post_type' => array('events'),
'order' => 'DESC',
);
$query = new WP_Query( $args_query );
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
$data = //do your stuff like
}
} else {
}
return $data;
wp_reset_postdata();
}
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0