0

I need to create a new route all which returns only the specified fields for all posts.

add_action( 'rest_api_init', function () {

     register_rest_route( 'custom', 'all' ,array(

        'methods'  => 'GET',
        'callback' => 'get_all'

     ) );

} );

I need to have for all posts, their id, title, link.

I'm unable to create my get_all function.

function get_all ( $params ){

    $posts = get_posts( 
        array( 
            'post_type' => 'post',
            'post_status' => 'publish'
        )
     );


      // parse all posts and for each post returns only the specified fields

     wp_reset_postdata();

     return rest_ensure_response( $data );

}
  • Why are you unable to create the function? What specifically isn't working? – Jacob Peattie Jan 25 at 16:59
  • Just remembered a similar post recently here – birgire Jan 25 at 17:00
0

Found! This function returns the specified fields for each post.

function get_all ( $params ){

     $posts = get_posts( array(
            'offset'      => 0,
            'post_status' => 'publish'
    ) );


    if ( empty( $posts ) ) {
        return null;
    }

    $posts_data = array();

    foreach( $posts as $post ) {

        $posts_data[] = (object) array( 
            'id' => $post->ID, 
            'date'      => $post->post_date,
            'date_gmt'  => $post->post_date_gmt,
            'modified'  => $post->post_modified,
            'title'     => $post->post_title,
            'content'   => $post->post_content,
            'category'  => get_the_category_by_ID($post->post_category[0]),
            'link'      => get_permalink($post),
        );
    }

    return $posts_data;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.