Question

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 );

}
Était-ce utile?

La solution

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;
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à wordpress.stackexchange
scroll top