Skip to content

Instantly share code, notes, and snippets.

@pinalj
Last active March 31, 2023 07:20
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pinalj/74ce42b2bd6753d34d1f5778a87bb3c9 to your computer and use it in GitHub Desktop.
Save pinalj/74ce42b2bd6753d34d1f5778a87bb3c9 to your computer and use it in GitHub Desktop.
Filtering Posts based on Author ID - REST API
<?php
add_action( 'rest_api_init', 'my_register_route');
function my_register_route() {
register_rest_route( 'my-route', 'my-posts/(?P<id>\d+)', array(
'methods' => 'GET',
'callback' => 'my_posts',
'args' => array(
'id' => array(
'validate_callback' => function( $param, $request, $key ) {
return is_numeric( $param );
}
),
),
'permission_callback' => function() {
return current_user_can( 'edit_others_posts' );
},
);
}
function my_posts( $data ) {
// default the author list to all
$post_author = 'all';
// if ID is set
if( isset( $data[ 'id' ] ) ) {
$post_author = $data[ 'id' ];
}
// 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