【问题标题】:Wordpress custom do_parse_request always returns 404Wordpress 自定义 do_parse_request 总是返回 404
【发布时间】:2019-04-09 10:01:42
【问题描述】:

所以我创建了自己的特殊do_parse_request 过滤器,它的效果非常好。拦截正确的请求以返回正确的内容,其他请求继续以它们正常的 WordPressy 方式。基本上,我在劫持某些 URL 以在正常的 WordPress 路由之外做一些自定义的事情。

除了...尽管内容正确,但响应始终是 404。

如果常规请求未完成,我是否缺少需要在 WordPress 中设置的内容?

add_filter('do_parse_request', function($do_parse, $wp) {
    //... bunch of code to dynamically determine 
    //if a page belongs to custom source, which works
    if ($ismypage){
        remove_action('template_redirect', 'redirect_canonical');
        $wp->query_vars['post_type'] = 'my_post_type';
        $wp->query_vars['name'] = $mypagename;
        return false;
        //always a 404, even though I get expected content...
    } 
    return $do_parse;
}

试过了:

四处逛逛,在返回 false 之前查看了 WP_REST_Response。获取:

        $testResponse = new WP_REST_Response();
        var_dump($testResponse->get_headers());
        //empty array
        var_dump($testResponse->get_status());
        //int 200

在网络上挖掘更多内容后发现了一个文字 status_header 方法。甚至尝试过header("HTTP/1.1 200 Success")

        //... right before return false
        status_header(200);
        //still gets 404 on the page, still gets correct content
        header("HTTP/1.1 200 Success");
        //same issue

我开始认为这不是我的问题的原因...

【问题讨论】:

    标签: php wordpress response-headers


    【解决方案1】:

    所以呃……这行得通。不是 1000% 确定为什么,除此之外,必须在其他东西确定这是 404 之后调用它。因此,一个更好的答案值得赞赏,但这至少克服了 404 响应......

    //right before return false in my do_parse_request filter
    do_action( 'template_redirect' );
    

    然后还添加一个模板重定向过滤器并将其设置为 200:

    add_filter("template_redirect", function(){
        status_header(200);
    });
    

    【讨论】:

      猜你喜欢
      • 2013-11-23
      • 1970-01-01
      • 2019-11-03
      • 2021-08-05
      • 2015-07-31
      • 2010-09-25
      • 2016-02-04
      • 2014-05-29
      • 2021-07-28
      相关资源
      最近更新 更多