Skip to content

Instantly share code, notes, and snippets.

@pravnkay
Created December 18, 2019 21:20
Show Gist options
  • Save pravnkay/60c3423b833f7e99e67b85a2c9998ad7 to your computer and use it in GitHub Desktop.
Save pravnkay/60c3423b833f7e99e67b85a2c9998ad7 to your computer and use it in GitHub Desktop.
WP-API - Post by Category
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);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment