Wordpress API - 如何以单数形式与多个自定义帖子类型响应显示不同的数据

问题描述 投票:0回答:1

我有一个自定义的帖子类型'产品',它在API响应中返回了大量数据,最多400个帖子有很多节点。几乎所有数据都来自高级自定义字段(我使用ACF到API插件来公开它)。

在“产品”页面上,我只需要显示产品的标题和图像。有没有办法在使用https://example.com/wp-json/wp/v2/product请求所有产品时删除所有其他字段,但在使用https://example.com/wp-json/wp/v2/product/123请求特定产品时保留该数据?

wordpress api custom-post-type wp-api
1个回答
1
投票

您最好为所有产品创建自定义端点。在自定义插件中添加以下代码或将其添加到theme.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;                   
}
© www.soinside.com 2019 - 2024. All rights reserved.