In the first post of my AngularJS WordPress theme series, I set the post title to link to {{post.ID}}
so I can get a single post with the default route in WP API: /posts/<id>
.
Couple days ago Ryan asked me can we use slug
instead of ID
, and reminded me that in the original demo video (Eric Wolfe: Building a WordPress Theme Using AngularJS), Eric did use the slug
rather than ID
. At first I replied to him it’s because Eric used the JSON API not WP API (JSON REST API), by default the WP API can only get post by ID.
The answer was not so persuasive I thought it’s better to double checked. Luckily I found the right answer in Josh‘s article on Torque: we can get posts by slug with filter
parameter.
So here are the snippets you’ll need to update, if you prefer to use slug in our project files (from my previous tutorials):
1. js/scripts.js
- line 6: Change
/:ID
to/:slug
- line 16: Change
'wp-json/posts/' + $routeParams.ID
to'wp-json/posts/?filter[name]=' + $routeParams.slug
- line 17: With this approach, we’ll get an array of posts, so we set
$scope.post = res[0]
.
2. partials/main.html
- line 5: Change
{{post.ID}}
to{{post.slug}}
You can get the full code from a branch of the project repo. I hope short posts like this can also help readers understand better about AngularJS and WordPress, especially how to accomplish a specific task. See you soon.
Leave a Reply