Make WP api json response use localhost instead of development url

Hi,

I noticed that when using the Wordpress api in developing mode (yarn start) the api response (wp-json/wp/v2) is using the development domain instead of localhost:3000. Does anyone know how to make wp json api response show links with localhost:3000 as the base domain? Because everytime I click on links that are based on the api response I’m going to the development domain instead of localhost:3000

I also tried to find out how to make the paths in the response relative instead of absolute, but I failed to find how to do it.

I hope anyone can steer me in the right direction, thanks

Nick

Edit: I found a another topic with the same problem but it contains no solution unfortunately: Not proxying wp-rest api requests

After having scouted the whole internet I came up with a sort of workaround. The workaround is probably wrong in many ways but its working for me. In functions.php I added the following snippet:

if(env('WP_ENV') == 'development') {
  function apply_proxy_to_api_links( $result ) {
    foreach ( $result->data as &$data_entry ) {
      if(array_key_exists('link', $data_entry))
      {
        $new_link_value     = str_replace( home_url(), 'https://localhost:3000', $data_entry['link'] );
        $data_entry['link'] = $new_link_value;
      }
    }
    unset( $data_entry );
    return $result;
  }

  add_filter( 'rest_post_dispatch', 'apply_proxy_to_api_links', 10, 3 );
}

This replaces the domain part in the link for each post. And it will only work if you’re running with yarn start. Improvements are very welcome.

1 Like