Wordpress API-如何在单数和复数自定义post类型响应中显示不同的数据

Wordpress API-如何在单数和复数自定义post类型响应中显示不同的数据,wordpress,api,custom-post-type,wp-api,Wordpress,Api,Custom Post Type,Wp Api,我有一个自定义的post类型“product”,它在API响应中返回大量数据,最多400篇包含大量节点的post。几乎所有的数据都来自高级自定义字段(我使用ACF到API插件来公开它) 在“产品”页面上,我只需要显示产品的标题和图像。当使用请求所有产品时,是否有方法删除所有其他字段https://example.com/wp-json/wp/v2/product,但在使用https://example.com/wp-json/wp/v2/product/123?您最好为所有产品创建一个自定义端点

我有一个自定义的post类型“product”,它在API响应中返回大量数据,最多400篇包含大量节点的post。几乎所有的数据都来自高级自定义字段(我使用ACF到API插件来公开它)


在“产品”页面上,我只需要显示产品的标题和图像。当使用
请求所有产品时,是否有方法删除所有其他字段https://example.com/wp-json/wp/v2/product
,但在使用
https://example.com/wp-json/wp/v2/product/123

您最好为所有产品创建一个自定义端点。将下面的代码添加到您的自定义插件中,或者将其添加到主题的functions.php中(不过我建议使用自定义插件方法)

然后,您可以使用
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;                   
}