diff --git a/src/RequestDispatcher.php b/src/RequestDispatcher.php index 3a36435..a3c968e 100644 --- a/src/RequestDispatcher.php +++ b/src/RequestDispatcher.php @@ -176,6 +176,10 @@ private function shouldReturnJson() return ( isset($_GET['json']) || $this->outputFormat === 'json' || + ( + ! empty( $_SERVER['HTTP_ACCEPT'] ) && + strtolower( $_SERVER['HTTP_ACCEPT'] ) == 'application/json' + ) || ( ! empty( $_SERVER['HTTP_X_REQUESTED_WITH'] ) && strtolower( $_SERVER['HTTP_X_REQUESTED_WITH'] ) == 'xmlhttprequest' && diff --git a/tests/unit/RouterTest.php b/tests/unit/RouterTest.php index 2a73575..3595c6a 100644 --- a/tests/unit/RouterTest.php +++ b/tests/unit/RouterTest.php @@ -1380,6 +1380,32 @@ function testHandlerReturningRespondToJsonToXmlHttpRequest() ); } + function testHandlerReturningRespondToJsonToAcceptJson() + { + $_SERVER['HTTP_ACCEPT'] = 'application/json'; + + \WP_Mock::wpFunction( 'wp_send_json', array( + 'times' => 1, + 'return' => 'json data output', + ) ); + + $router = Router::create(); + + $router->get('users', 'get_users', function(){ + return ['respond_to' => [ + 'json' => 'irrelevant data as wp_send_json return data is mocked above', + 'html' => function(){ + return 'users view loaded'; + } + ]]; + }); + + $this->assertEquals( + 'json data output', + $router->dispatch('GET', 'users') + ); + } + function testHandlerReturningRespondToJsonToRequestWithJsonGetParam() { \WP_Mock::wpFunction( 'wp_send_json', array(