hooks - How to create callback function which returns all posts with specific data?

admin2025-06-03  2

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

}

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

}
Share Improve this question asked Jan 25, 2019 at 16:23 cmiicmii 1215 bronze badges 2
  • Why are you unable to create the function? What specifically isn't working? – Jacob Peattie Commented Jan 25, 2019 at 16:59
  • Just remembered a similar post recently here – birgire Commented Jan 25, 2019 at 17:00
Add a comment  | 

1 Answer 1

Reset to default 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;
}
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1748958155a315156.html

最新回复(0)