WordPress REST endpoint to accept special
Issue: unrecognized character in URL
1 2 3 4 5 6 7 8 |
{ code: "rest_no_route", message: "No route was found matching the URL and request method", data: { status: 404 } } |
Expected Usage
1 2 3 4 5 |
// type this to address bar http://localhost/wp-json/search/posts/this is a test // once entered, it will turn into url encoded string http://localhost/wp-json/search/posts/this%20is%20a%20test |
Output
1 |
"this is a test" |
WordPress register custom REST API
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
/** * Initialize APIs */ public function init_APIs(){ add_action('rest_api_init', array($this, 'register_route')); } /** * Register API route * Setup API at /wp-json/search/posts/{value} */ public function register_route(){ $args = array( 'methods' => 'GET', 'callback' => array($this, 'api_get_posts'), ); register_rest_route( 'search', '/posts/(?P<value>[\w+].+)', $args ); } /** * API callback:: get posts by string * @param Array $args['value'] * @return JSON */ public function api_get_posts($args){ $value = str_replace('%20', ' ', $args['value']); return $value; } |