wordpressapicustom-post-typewp-api

Wordpress API - how to show different data in singular vs plural custom post type responses


I have a custom post type 'product' that returns quite a lot of data in the API response, up to 400 posts with a lot of nodes. Almost all the data is coming from advanced custom fields (I'm using ACF to API plugin to expose it).

On the 'products' page, I only need to show the title & image of the product. Is there a way to remove all other fields when requesting all products with https://example.com/wp-json/wp/v2/product, but leave that data in place when requesting a specific product with https://example.com/wp-json/wp/v2/product/123 ?


Solution

  • You better create a custom endpoint for all products. Add the code below in your custom plugin or add it in functions.php of theme (I will recommend the custom plugin approach though)

    You can then access it using https://example.com/wp-json/custom/v1/all-products

    add_action( 'rest_api_init', 'rest_api_get_all_products' );
    
    function rest_api_get_all_products() {
        register_rest_route( 'custom/v1', '/all-products', array(
            'methods'  => WP_REST_Server::READABLE,
            'callback' => 'rest_api_get_all_products_callback',
            'args' => array(
                'page' => array(
                    'sanitize_callback' => 'absint'
                ),
                'posts_per_page' => array(
                    'sanitize_callback' => 'absint'
                )
            )
        ));
    }
    
    function rest_api_get_all_products_callback( $request ) {
    
        $posts_data = array();
    
        $paged = $request->get_param( 'page' );
        $posts_per_page = $request->get_param( 'posts_per_page' );
    
        $paged = ( isset( $paged ) || ! ( empty( $paged ) ) ) ? $paged : 1; 
        $posts_per_page = ( isset( $posts_per_page ) || ! ( empty( $posts_per_page ) ) ) ? $posts_per_page : 10;
    
        $query = new WP_Query( array(
                'paged' => $paged,
                'posts_per_page' => $posts_per_page,
                'post_status'    => 'publish',
                'ignore_sticky_posts' => true,
                'post_type' => array( 'product' )
            )
        );
        $posts = $query->posts;
    
        if( empty( $posts ) ){
            return new WP_Error( 'no_post_found', 'No Products Found.', array( 'status' => 404 ) );
        }
    
            foreach( $posts as $post ) {
                $id = $post->ID; 
                $post_thumbnail = ( has_post_thumbnail( $id ) ) ? get_the_post_thumbnail_url( $id ) : null;
    
    
                $posts_data[] = (object) array( 
                    'id' => intval($id),
                    'title' => $post->post_title,
                    'featured_img' => $post_thumbnail
                );
            }
        $response  = rest_ensure_response( $posts_data );      
        return $response;                   
    }