Created
December 1, 2017 06:33
-
-
Save pinalj/5763b40d0e9f6656a49f41f55cf07a73 to your computer and use it in GitHub Desktop.
Display all posts using REST API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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 ); | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You have some mistakes in this code... Please check it out... You have missed some brackets...