You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让自定义WordPress REST接口返回与内置接口一致的媒体库全量信息

Solution: Match Built-in Media REST API Output & Bypass 100 Item Limit

Great question! The built-in /wp/v2/media endpoint handles a ton of critical formatting under the hood—like attaching post relationships, generating responsive image URLs, parsing metadata, and standardizing the response structure. When building a custom endpoint from scratch, you miss all that out-of-the-box logic, which is why your output doesn’t match. Plus, the 100-item posts_per_page limit is enforced at the route registration level for default WP REST endpoints, but we can get around that in custom code.

Here are two reliable approaches to get the exact same response as the built-in endpoint, while setting your own item limit:

Approach 1: Reuse the Built-in Media REST Controller (Simplest Method)

This method leverages WordPress’s existing WP_REST_Media_Controller class to handle all the formatting and logic, so you don’t have to replicate it. It’s the easiest way to guarantee your custom endpoint returns identical data to /wp/v2/media.

Add this code to your theme’s functions.php or a custom plugin:

add_action('rest_api_init', function () {
    // Register your custom route
    register_rest_route('custom/v1', '/media/svg', [
        'methods' => WP_REST_Server::READABLE,
        'callback' => 'custom_get_svg_media',
        // Adjust permission callback to match your needs (e.g., current_user_can('edit_posts'))
        'permission_callback' => '__return_true',
    ]);
});

function custom_get_svg_media($request) {
    // Initialize the default media REST controller
    $media_controller = new WP_REST_Media_Controller();

    // Define your parameters (bypass the 100-item limit here)
    $query_params = [
        'post_mime_type' => 'image/svg+xml', // More precise than searching for ".svg"
        'per_page' => 200, // Set your desired limit (no 100 cap here)
        'post_status' => 'inherit',
        'orderby' => 'date',
        'order' => 'DESC',
    ];

    // Create a REST request object to mimic the built-in endpoint's context
    $rest_request = new WP_REST_Request('GET', '/wp/v2/media');
    $rest_request->set_query_params($query_params);

    // Let the controller handle the heavy lifting
    $response = $media_controller->get_items($rest_request);

    // Return the properly formatted response
    return rest_ensure_response($response);
}

Why this works:

  • The WP_REST_Media_Controller::get_items() method runs all the same logic as the built-in endpoint, so your response will include every field (like media_details, post, guid, etc.) exactly as you’d get from /wp/v2/media.
  • We bypass the 100-item limit because we’re directly calling the controller method instead of going through the default route’s parameter validation.

Approach 2: Manually Query & Format Attachments (More Flexible)

If you need more control over the query or response, you can manually fetch attachments and use the controller’s formatting methods to match the built-in output:

add_action('rest_api_init', function () {
    register_rest_route('custom/v1', '/media/svg', [
        'methods' => WP_REST_Server::READABLE,
        'callback' => 'custom_get_svg_media',
        'permission_callback' => '__return_true',
    ]);
});

function custom_get_svg_media($request) {
    $per_page = $request->get_param('per_page') ?: 200;

    // Build your custom WP_Query
    $query_args = [
        'post_type' => 'attachment',
        'post_mime_type' => 'image/svg+xml',
        'posts_per_page' => $per_page,
        'post_status' => 'inherit',
        'orderby' => 'date',
        'order' => 'DESC',
    ];

    $attachments_query = new WP_Query($query_args);

    if (!$attachments_query->have_posts()) {
        return rest_ensure_response([]);
    }

    $media_controller = new WP_REST_Media_Controller();
    $formatted_items = [];

    // Format each attachment using the built-in controller logic
    foreach ($attachments_query->posts as $attachment) {
        $formatted_item = $media_controller->prepare_item_for_response($attachment, $request);
        $formatted_items[] = $media_controller->prepare_response_for_collection($formatted_item);
    }

    // Return response with pagination headers (matches built-in endpoint)
    $response = rest_ensure_response($formatted_items);
    $total_items = $attachments_query->found_posts;
    $total_pages = ceil($total_items / $per_page);

    $response->header('X-WP-Total', $total_items);
    $response->header('X-WP-TotalPages', $total_pages);

    return $response;
}

Key Notes:

  • Use post_mime_type instead of search=.svg for more accurate SVG filtering—this avoids matching attachments with ".svg" in their filename but incorrect MIME types.
  • Adjust the permission_callback to restrict access (e.g., current_user_can('manage_options') for admins only) instead of using __return_true in production.
  • Be cautious with very large per_page values—fetching hundreds of attachments at once can impact site performance.

Final Result

Either approach will return a response identical to the built-in /wp/v2/media endpoint, but with your custom item limit. You can test your new endpoint at your-site.com/wp-json/custom/v1/media/svg.

内容的提问来源于stack exchange,提问作者Peter Breen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:37:32