自定义终结点和X-WP-TotalPages(标题)

时间:2017-06-13 作者:jshwlkr

我有一个自定义端点定义如下:

    add_action( \'rest_api_init\', function () {
        register_rest_route( \'menc/v1\', \'/crosscat/(?P<dept>[\\w-]+)/(?P<cat>[\\w-]+)\', array(
            \'methods\' => \'GET\',
            \'callback\' => \'dept_cat_api\',
            \'args\' => array(
                \'dept\' => array(
                    \'sanitize_callback\' => function($param, $request, $key) {
                        return sanitize_text_field( $param );
                    }
                ),
                \'cat\' => array(
                    \'sanitize_callback\' => function($param, $request, $key) {
                        return sanitize_text_field( $param );
                    }
                ),
                \'per_page\' => array(
                    \'default\' => 10,
                    \'sanitize_callback\' => \'absint\',
                ),
                \'page\' => array(
                    \'default\' => 1,
                    \'sanitize_callback\' => \'absint\',
                ),
                \'orderby\' => array(
                    \'default\' => \'date\',
                    \'sanitize_callback\' => \'sanitize_text_field\',
                ),
                \'order\' => array(
                    \'default\' => \'desc\',
                    \'sanitize_callback\' => \'sanitize_text_field\',
                ),
            ),
        ) );
    } );

    function dept_cat_api( $request ) {
        $args = array(
            \'post_type\' => \'post\',
            \'tax_query\' => array(
                \'relation\' => \'AND\',
                array(
                    \'taxonomy\' => \'crosspost\',
                    \'field\'    => \'slug\',
                    \'terms\'    => array( $request[\'dept\'] ),
                ),
                array(
                    \'taxonomy\' => \'category\',
                    \'field\'    => \'slug\',
                    \'terms\'    => array( $request[\'cat\'] ),
                ),
            ),
            \'per_page\' => $request[\'per_page\'],
            \'page\' => $request[\'page\'],
            \'orderby\' => $request[\'orderby\'],
            \'order\' => $request[\'order\']
        );

        $posts = get_posts( $args );

        if ( empty( $posts ) ) return new WP_Error( \'no_posts\', \'Invalid term(s)\', array( \'status\' => 404 ) );

        $controller = new WP_REST_Posts_Controller(\'post\');

        foreach ( $posts as $post ) {
            $response = $controller->prepare_item_for_response( $post, $request );
            $data[] = $controller->prepare_response_for_collection( $response );  
        }

// return results
        return new WP_REST_Response($data, 200);

    }
我有点问题。当我打电话给路线时,所有内容似乎都很好,但是X-WP-TotalPagesX-WP-Total 返回空响应。

    object(Requests_Utility_CaseInsensitiveDictionary)#991 (1) {
      ["data":protected]=>
      array(20) {
        ["server"]=>
        string(5) "nginx"
        ["date"]=>
        string(29) "Wed, 14 Jun 2017 14:07:51 GMT"
        ["content-type"]=>
        string(31) "application/json; charset=UTF-8"
        ["content-length"]=>
        string(6) "104787"
        ["expires"]=>
        string(29) "Thu, 19 Nov 1981 08:52:00 GMT"
        ["pragma"]=>
        string(8) "no-cache"
        ["x-robots-tag"]=>
        string(7) "noindex"
        ["link"]=>
        string(65) "; rel="https://api.w.org/""
        ["x-content-type-options"]=>
        string(7) "nosniff"
        ["access-control-expose-headers"]=>
        string(27) "X-WP-Total, X-WP-TotalPages"
        ["access-control-allow-headers"]=>
        string(27) "Authorization, Content-Type"
        ["allow"]=>
        string(3) "GET"
        ["x-cacheable"]=>
        string(5) "SHORT"
        ["vary"]=>
        string(22) "Accept-Encoding,Cookie"
        ["cache-control"]=>
        string(28) "max-age=600, must-revalidate"
        ["accept-ranges"]=>
        string(5) "bytes"
        ["x-cache"]=>
        string(6) "HIT: 1"
        ["x-pass-why"]=>
        string(0) ""
        ["x-cache-group"]=>
        string(6) "normal"
        ["x-type"]=>
        string(7) "default"
      }
    }
理想情况下,我需要两者都填充,但我可以凑合一个。我假设WordPress通过控制器计算/填充这些。我必须手动填充它们吗?我做错什么了吗?我是否遇到错误?

2 个回复
最合适的回答,由SO网友:birgire 整理而成

我快速查看了一下,下面是如何在WP_REST_Posts_Controller::get_items() 方法:

$response  = rest_ensure_response( $posts );
// ...
$response->header( \'X-WP-Total\', (int) $total_posts );
$response->header( \'X-WP-TotalPages\', (int) $max_pages );
// ...
return $response;
其中:

$total_posts = $posts_query->found_posts;
我们可以使用as@jshwlkrsuggested:

$max_pages = $posts_query->max_num_pages;
您可以通过使用WP_Query 而不是get_posts().

感谢DenisUyedacorrecting the typo.

SO网友:suprio

根据上面的答案,我使用了这个代码,它对我有用。

$query = new WP_Query(array());

$posts = $query->get_posts();

$total_posts = $query->found_posts;
$max_pages = $query->max_num_pages;
$returned =  new WP_REST_Response($posts, 200);
$returned->header( \'X-WP-Total\', $total_posts );
$returned->header( \'X-WP-TotalPages\', $max_pages );
return $returned;

结束

相关推荐

How to modify admin headers

我正在尝试创建一个主题设置导出脚本,该脚本base\\u 64对主题选项进行编码,并允许用户将其下载为文本文件。我看到一个帖子(What is the best way to export and import theme options?) 这涉及检查查询变量,然后使用“template\\u redirect”操作重定向用户。然而,看起来这个操作只在站点的前端可用(不在管理中)。将操作添加到选项框架的构造函数中并没有任何作用。我可以通过将我的函数绑定到“admin\\u init”来启动它,但到那时,