Make WP api json response use localhost instead of development url

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