WP REST API--如何更改HTTP响应状态代码?

时间:2017-01-21 作者:Gasim

我有一个自定义端点,我想在某些场景中将HTTP响应状态更改为404(例如post不存在)。我该怎么做?以下是自定义端点的示例:

function af_news_single( \\WP_REST_Request $data ) {
    global $wpdb;

    $year = (int) $data[\'year\'];
    $month = (int) $data[\'month\'];
    $day = (int) $data[\'day\'];
    $slug = $data[\'slug\'];

    $date = "{$year}-{$month}-{$day}";

    $news = $wpdb->get_row(
        $wpdb->prepare(
            "SELECT
                DATE_FORMAT(post_date, %s) as `post_date`,
                `post_title`,
                `post_name`,
                `post_content`
             FROM {$wpdb->posts}
             WHERE
                `post_status` = \'publish\' AND
                `post_type` = \'post\' AND
                `post_name` = %s AND
                `post_date` BETWEEN %s AND %s + INTERVAL 1 DAY
             LIMIT 1
             ", \'%Y-%m-%dT%TZ\', $slug, $date, $date
        )
    );

    if ( $news ) {
        $news->post_title = qtranxf_translate( $news->post_title );
        $news->post_content = wpautop( qtranxf_translate( $news->post_content ) );
    } else { /* How to change response code? */ }

    return [ \'data\' => $news ];
}
如何更改此函数中的响应代码?

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

您可以返回WP_Error 对象,在其中定义状态代码。以下是the REST API documentation:

function my_awesome_func( $data ) {
    $posts = get_posts( array(
        \'author\' => $data[\'id\'],
    ) );

    if ( empty( $posts ) ) {
        return new WP_Error( \'awesome_no_author\', \'Invalid author\', array( \'status\' => 404 ) );
    }

    return $posts[0]->post_title;
}
在您的情况下,您可以执行以下操作:

return new WP_Error( \'page_does_not_exist\', __(\'The page you are looking for does not exist\'), array( \'status\' => 404 ) );

SO网友:Walf

最简单的方法是:

return new WP_REST_Response(null, 404);
注意:这仍然是一个JSON响应,包含null 就像身体一样。您可以返回更有用的数据结构,其中包含错误代码/消息等,或者hook into the REST output filters 输出空白text/plain 回答

SO网友:Piotr Kucułyma

我 WoULD NoT UsE:

&#十、A.;
RETURN NEW WP_REsT_REsPoNsE(NULL, 4.04.);&#十、A.;
&#十、A.;

我 HA.D A.N 我ssUE W我TH HosT我NG PRo五、我DER WHEN 我 UsED sTA.TUs CoDEs 我N TH我s FUNCT我oN. soMEHoW sETT我NG sTA.TUs CoDE TR我GGERED MoD_REWR我TE REsPoNsE.

&#十、A.;
MEssA.GE: A.CCEss DEN我ED W我TH CoDE 4.06. (PHA.sE 3.). TEsT \'REQUEsT_UR我|REQUEsT_HEA.DERs|REQUEsT_HEA.DERs_NA.MEs|A.RGs|A.RGs_NA.MEs|REQUEsT_BODY\' A.GA.我NsT \'!@五、A.L我DA.TEBYTERA.NGE 0-3.1.\' 我s TRUE.&#十、A.;
&#十、A.;

我T M我GHT NoT BE A.ND 我ssUE W我TH WoRDPREss BUT Us我NG:

&#十、A.;
RETURN NEW WP_REsT_REsPoNsE(NULL);&#十、A.;
&#十、A.;

soL五、ED THE PRoBLEM.

&#十、A.;

我\'LL JUsT LEA.五、E 我T HERE 我N CA.sE A.NYoNE ENCoUNTERs sA.ME PRoBLEM.

&#十、A.;

相关推荐

Php致命错误:无法将WP_REST_RESPONSE类型的对象用作wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php中

我向WordPress添加了一个自定义端点,如下所示: add_action( \'rest_api_init\', function () { register_rest_route( \'menc/v1\', \'/crosscat/(?P[\\w-]+)/(?P[\\w-]+)\', array( \'methods\' => \'GET\', \'callback\' => \'dept_cat_api\',&#x