Skip to content

Instantly share code, notes, and snippets.

@pinalj
Created December 1, 2017 06:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pinalj/5763b40d0e9f6656a49f41f55cf07a73 to your computer and use it in GitHub Desktop.
Save pinalj/5763b40d0e9f6656a49f41f55cf07a73 to your computer and use it in GitHub Desktop.
Display all posts using REST API
<?php
add_action( 'rest_api_init', 'my_register_route');
function my_register_route() {
register_rest_route( 'my-route', 'my-posts', array(
'methods' => 'GET',
'callback' => 'my_posts',
'permission_callback' => function() {
return current_user_can( 'edit_others_posts' );
},
);
}
function my_posts() {
// default the author list to all
$post_author = 'all';
// get the posts
$posts_list = get_posts( array( 'type' => 'post', 'author' => $post_author ) );
$post_data = array();
foreach( $posts_list as $posts) {
$post_id = $posts->ID;
$post_author = $posts->post_author;
$post_title = $posts->post_title;
$post_content = $posts->post_content;
$post_data[ $post_id ][ 'author' ] = $post_author;
$post_data[ $post_id ][ 'title' ] = $post_title;
$post_data[ $post_id ][ 'content' ] = $post_content;
}
wp_reset_postdata();
return rest_ensure_response( $post_data );
}
?>
@zonayedpca
Copy link

You have some mistakes in this code... Please check it out... You have missed some brackets...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment