Use the above function in functions.php file to get all posts under a particular category by that category slug
Access url https://your-site.com/wp-json/idapi/v1/posts/{category-slug-without-braces}
Use the above function in functions.php file to get all posts under a particular category by that category slug
Access url https://your-site.com/wp-json/idapi/v1/posts/{category-slug-without-braces}
| add_action('rest_api_init', function () { | |
| register_rest_route( 'idapi/v1', 'posts/(?P<category_name>[-\w]+)',array( | |
| 'methods' => 'GET', | |
| 'callback' => 'get_posts_by_category_name' | |
| )); | |
| }); | |
| function get_posts_by_category_name($request) { | |
| $args = array( | |
| 'category_name' => $request['category_name'] | |
| ); | |
| $posts = get_posts($args); | |
| if (empty($posts)) { | |
| return new WP_Error( 'empty_category', 'there is no post in this category', array('status' => 404) ); | |
| } | |
| $post_data = array(); | |
| $i = 0; | |
| foreach( $posts as $post) { | |
| $post_id = $post->ID; | |
| $post_title = remove_html_comments($post->post_title); | |
| $post_content = remove_html_comments($post->post_content); | |
| $post_data[ $i ][ 'id' ] = $post_id; | |
| $post_data[ $i ][ 'title' ] = $post_title; | |
| $post_data[ $i ][ 'content' ] = $post_content; | |
| $i++; | |
| } | |
| $response = new WP_REST_Response($post_data); | |
| $response->set_status(200); | |
| return $response; | |
| } | |
| function remove_html_comments($content = '') { | |
| return preg_replace('/<!--(.|\s)*?-->/', '', $content); | |
| } |