WP API and ngRoute for the category

I’m rebuilding my WordPress site as a SPA based in AngularJS with WP API. At the moment in wordpress my post has a permalink structure like /%category%/%postname%/ and I want to keep it in the new site, so, for example assuming that I have two category like tracks and articles my url will be /tracks/my-title or /articles/new-title. This means that my-title post has tracks as a category and new-title post has articles as category.

For dealing with this, in my new AngularJS site, I’m using ngRoute for handle the request and gives each category a related partial/controller.

    .when('/tracks/:slug', {
        templateUrl: myLocalized.partials + 'content.html',
        controller: 'Content'
    .when('/articles/:slug', {
        templateUrl: myLocalized.partials + 'articles.html',
        controller: 'Articles'

This is the controller for Articles, which is quite similar to the Content’s controller.

//Articles controller
app.controller('Articles', ['$scope', '$routeParams', '$http', function($scope, $routeParams, $http) {
    $http.get('wp-json/wp/v2/posts?slug=' + $routeParams.slug).success(function(res) {
        $scope.post = res[0];
        document.querySelector('title').innerHTML =  res[0].title.rendered + ' | Going Solo ';
    }).error(function(res, status) {
        if (status === 404) {
            $scope.is404 = true;
            document.querySelector('title').innerHTML = 'Page not found | Going Solo';
            $scope.errorMessage = 'Error: ' + res[0].message;

This works great, if you look for /tracks/my-title it shows the my-title post with the tracks template. But I guess this is a dumb solution, cause the template it’s not specifically related to the category, in fact you can look for /articles/my-title and display the post (which has tracks category) using the articles controller.

Is there something smarter to handle this?

Read more here: WP API and ngRoute for the category

Leave a Reply

Your email address will not be published. Required fields are marked *