A reader of my Building themes with AngularJS and JSON REST API series asked me how to make image links in WordPress work with AngularJS. This is a very good question that you must bump into when building your own AngularJS WordPress theme.
By default, when inserting an image to the editor with “Add Media” button, WordPress will set the “Link To” to “Attachment Page” or “Media File”. In the following example I’ll be showing you how to make the image linked to “Media File” work with AngularJS. In such case the source HTML of image link will look like this:
Linking an image to it’s original file URL will make our AngularJS theme work much easier that we don’t have to set another route to attachment page. We just need to make sure Angular won’t intercept the image file URL by adding
target attribute to the
a element. You can do so by hooking into the
Just add the code above to your
functions.php. After that, the image link will be free from being rewritten by Angular, the source HTML of image link will become:
To know why exactly this worked, explanation from official Angular document should help:
In cases like the following, links are not rewritten; instead, the browser will perform a full page reload to the original link.
- Links that contain
<a href="/ext/link?a=b" target="_self">link</a>
- Absolute links that go to a different domain
- Links starting with ‘/’ that lead to a different base path
I’m a senior web developer helping clients build their websites to grow businesses. Currently I’m based in Taipei, Taiwan.
I write things about WordPress, AngularJS and life. Whenever you’d like to find someone to talk about these topics, just get in touch!