我向WordPress添加了一个自定义端点,如下所示:
add_action( \'rest_api_init\', function () {
register_rest_route( \'menc/v1\', \'/crosscat/(?P[\\w-]+)/(?P[\\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 );
}
),
),
) );
} );
function dept_cat_api( $data ) {
$args = array(
\'post_type\' => \'post\',
\'tax_query\' => array(
\'relation\' => \'AND\',
array(
\'taxonomy\' => \'crosspost\',
\'field\' => \'slug\',
\'terms\' => array( $data[\'dept\'] ),
),
array(
\'taxonomy\' => \'category\',
\'field\' => \'slug\',
\'terms\' => array( $data[\'cat\'] ),
),
),
);
$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\');
$response = array();
foreach ( $posts as $post ) {
$data = $controller->prepare_item_for_response( $post, $data );
$response[] = $controller->prepare_response_for_collection( $data );
}
// return results
return new WP_REST_Response($response, 200);
}
cherry根据特定自定义分类法中类别和术语的交集来挑选帖子。在我的本地开发环境中,这会返回我期望的帖子或404响应。在生产上,它返回500 http错误,错误日志报告
PHP致命错误:无法将WP\\u REST\\u Response类型的对象用作/WP includes/REST api/endpoints/class WP REST posts控制器中的数组。php在线1554
我不确定这是否是服务器问题,或者是否有我看不到的错误。一个做同样事情的类似函数,使用标签而不是类别,效果很好。
最合适的回答,由SO网友:jshwlkr 整理而成
没有人指出我错误地使用了“$数据”。
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\'] ),
),
),
);
$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);
}