代码之家  ›  专栏  ›  技术社区  ›  geochanto

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

  •  0
  • geochanto  · 技术社区  · 7 年前

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

    https://example.com/wp-json/wp/v2/product ,但在请求具有 https://example.com/wp-json/wp/v2/product/123 ?

    0 回复  |  直到 7 年前
        1
  •  1
  •   Ehsan    7 年前

    最好为所有产品创建一个自定义端点。将下面的代码添加到自定义插件或将其添加到函数.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;                   
    }
    
    推荐文章