My Tutorials On Building Themes With AngularJS and WP REST API

AngularJS-large

Since October 2014, I developed a new hobby on building a WordPress theme with AngularJS. If you’re interested in “why” rather than “how”, honestly I can’t say there’re plenty of advantages about this approach/stack bla bla bla… Though there do be some in my opinion.

If you’re interested in my learning path, I’d love to share so I’ve written a series of tutorials for you. You might spend around 5 to 20 minutes on each post and I try my best not to bore you.

Any suggestion or feedback will be very much welcome. Here’s the list of my articles:

  1. Using AngularJS and JSON API in Your WordPress Theme:
    An introduction to use the WP REST API and AngularJS in a WordPress theme. I wrote it based on a tutorial video from WordPress.tv – Eric Wolfe: Building a WordPress Theme Using AngularJS, but added my own flavors. This post is now listed on Resources section at WP-API.org, which might lead some of you to this repository.
  2. AngularJS WordPress Theme: Display Post Content with ngBindHtml:
    You might be wondering why AngularJS displayed post content with HTML tags but not rendered them. In this tutorial you’ll find the answer and learn two approaches to solve it.
  3. Use AngularJS Custom Directives In A WordPress Theme:
    Custom directives are very powerful in AngularJS. I’ll show you how to create a search form directive <search-form> in this theme, and make it work like the WordPress built-in template tag get_search_form().
  4. Minification Errors in My AngularJS WordPress Theme:
    After minifying AngularJS scripts, our theme suddenly stopped working. How did that happen? We’ll dig into another important concept called Dependency Injection (DI) in AngularJS.
  5. Using Slug To Get Single Post In AngularJS WordPress Theme:
    Everyone knows pretty links bring pretty SEO performance, so we shall add post slug to our permalink structure, right? I’ll get you all set in this short post.
  6. Making WordPress Admin Bar Work With AngularJS Theme:
    Oops, the WordPress admin bar dosen’t work with our AngularJS theme. Let’s see what we can do to fix it.
  7. Setting Page Title Dynamically In AngularJS WordPress Theme:
    Changing the page title dynamically is an important feature in our AngularJS WordPress Theme. We need to incorporate this feature into our theme.
  8. Filtering image_send_to_editor To Add Target Attribute To Link:
    If you insert an image link in the post content, it will work funny (not as expected) in our AngularJS theme. With a very short snippet, boom! The problem goes away.
  9. Category Pages In AngularJS WordPress Theme:
    Show me some category pages in this AngularJS WordPress theme, you said? Sure. I covered pretty much everything you need to know about this topic.
  10. Adding Slick Carousel To Your AngularJS WordPress Theme:
    Adding a slick carousel to your post to display all attached media can’t be easier with Angular Slick.
  11. Pagination In AngularJS WordPress Theme:
    My second tutorials on creating custom directives in AngularJS WordPress Theme. This time we’ll create a postsNavLink directive which works like the built-in WordPress template tag posts_nav_link(). They even take the same parameters!
  12. When Page Not Found In Your AngularJS WordPress Theme:
    A good developer should always keep an eye on error responses from the application. Let’s start with the popular “page not found” error and see how to deal with it.
  13. Improving Your AngularJS WordPress Theme With A Service:
    The first tutorial we talk about AngularJS
    servcies. We’ll introduce how to share data between controllers by creating a new service called WPService.
  14. Tidy Up Your AngularJS WordPress Theme With A Service:
    It’s the second post we talk about Angular services. We’ll see how to use the WPService to organize and share code across the theme, which helps us tidy up our code.
  15. Adding Fields To The JSON Response Of The WP REST API:
    This post is only 10% related to AngularJS, but you’ll learn how to better work with AngularJS just by manipulating the fields in the JSON response of the WP REST API.
  16. Getting Posts By Taxonomy Or Meta Field With WP-API v2.0:
    The WP-API v2.0 works in a more WP_Query way, but there’re still a few concepts need to be clarified. Wanna know how many query parameters are available? Let’s dig into the source of WP-API and WordPress.
  17. Upgrading Your AngularJS Theme To Work With WP API V2:
    The WP API v2 is almost ready so I’m upgrading the AngularJS theme project to work with it. Other than just changing the routes, you’ll be surprised how the version 2 differs from version 1.
  18. Cookie Authentication In A AngularJS WordPress Theme:
    I’ll walk you through what are cookie authentication, WordPress nonces and AngularJS $httpProvider.interceptors in this tutorial. By sending the nonce in the headers with each API requests, getting authenticated with WP API in a theme is actually very easy.
  19. Display Post Excerpt To The More Tag With WP API V2:
    Are you looking for a solution to display post excerpt based on the <!--more--> tag? I have some not-so-shiny tricks to show you.
  20. Getting Categories With Posts In A Single WP API Request:
    This short tutorial will show you how to add an extra field to the category route response, so you can get related posts for each category with just a single API call.
  21. Removing Content From WP API Response When Listing Posts:
    You can conditionally add or remove fields from WP API response. Sounds cool, huh?
Share the post:Tweet about this on TwitterShare on Google+9Share on Facebook58Share on LinkedIn6

116 Comments

Submit a comment
    • Hey Ryan, it looks very promising. I’ll finish the tutorials later and let you know my thoughts. Cheers.

  • Hi Yoren, your tutorials has been a huge help to me, i want to thank you about that, i was wondering if there is a way to the category JSON object come to me with an image property?, there is some plugins to add an image to categories but i need the image in the JSON object, have you had the same problem?

    • Hey T0T,

      If you need to get pages, you’ll need to use endpoint like “/wp-json/pages/” and “/wp-json/pages/2”. Let me know if it works for you. Thanks for your kind words!

  • yes, I hardcoded the specific ID of each individual page on menu items: “/pages/50” and then RouteProvider with “/pages/:ID'” and it runs. but “/pages/50” is so ugly to see it at the browser’s address bar. ;(
    It would be cleaner with slug. I tried to change /:ID by /:slug but not running.

    • To query a page with slug, just set the endpoint to “/wp-json/pages/?filter[name]=slug-here” in your controller. It will return pages in an array.

      • But for 15 different pages I should add “/wp-json/pages/?filter[name]=slug-here” 15 times. One for each.

  • /:slug 😉

    .when(‘/:slug’, {
    templateUrl: myLocalized.partials + ‘content.html’,
    controller: ‘Main’
    })

    • I’ll recommend that you use “/pages/:slug”, you’ll need to prefix for the route paths, or the routes might not work. (They’ll start acting weird when you set the default route with otherwise)

  • Yoren,

    Would you know how to implement a comment form using the wp-api and angularjs?

    And list the comments below that.

      • Thanks Yoren! I went ahead and went with Disqus so that I didn’t have to worry about using wordpress to administer my comments.

        • Would you be able to share with me how you accomplished implementing discus? I am currently only able to load a single discus thread for every post. Discus says to apply environment variables ‘this.page.url’ and ‘this.page.identifier’ in order to give each post its own thread, but I am having trouble accomplishing this due to the fact that I can’t get inline javascript to execute in my ui-router html templates. Any advice greatly appreciated.

  • Also it would be nice to make one http get request and use that data in the controllers rather than make http get request each time in ever route change.

    I added a service to do this for posts and it works really nice. It increased performance big time.

    • Yep, service is the ultimate way when we need to share data between controllers.

  • Nice tuts series! I’m busy creating an Angular2 app to replace my crurent WordPress theme.

    I will not make it a wp theme but a fully stand-alone app. My goal is to support an offline mode through service workers.

    • Hey Blub, the stand alone app is the approach I’ll definitely go in the future. Would love to know when your app is finish. The offline feature sounds really exiting!

  • Hi Yoren,

    I’m having issues filtering my custom posts by a custom taxomoy. I’ve tried easily over 50 different combinations. I would have thought one of the below would work
    wp-json/posts?type=events&filter[terms]=upcoming-events

    wp-json/posts?type[]=events&filter[taxonomy]=calendar&filter[terms]=upcoming-events. Any help is alway greatly appreciated?

  • Your tutorials are really helpful. I’m building an Angular theme for a page. Hope it will work. Thank you!

    • Hi! I installed the WP-d3 plugin for my charts, yet it won’t work on my Angular.js theme. I’ve successfully integrated d3.js on my Angular.js template, but when it is inside the page content using the plugin, there is no chart displayed.

      I’ve seen here similar questions on how to allow the scripts/plugins from the content. Is there a way to do it?

      Thanks!

      • Hey I think it’s related to the event delegation in Angular that because you load the post content later (after the d3 binds to the DOM elements), so it seems not working.

        I don’t use d3 myself so wish you best luck on googling the keywords like “angular d3 event delegation”. Cheers!

        • Oh my. I’m not used to having someone in the same timezone. I see, I’ll go check it out. Thank you!

  • Great Tutorial series.

    I have been playing with this for couple days now, fairly new to AngularJS.
    I deviated a bit, by using ngResource instead of $http.

    But i was wondering, in this series we are fetching data from the api. But what if we want to post data. Any thoughts/pointers on that?

  • I had a look at angularjs via codecademy and wasnæt too sure about it. Then I started learning WordPress and it seems so similar to what I saw in angular. Basically inserting template tags and php functions into html. Is this a false assumption? Iæm having a blast learning wordpress so Iæm really hoping it will make angular more easy to learn after a while.

  • Hi Yoren

    Thanks for these fantastic tutorials. I am relatively new to Angular and have been reading some of the concerns about Angular 2.0.

    Your strategy for wp-json api + Angular seems perfect for a project that I’m about to start, but I’m wondering if it makes sense to start a new (and possibly quite large) project before 2.0 is released.

    Do you plan to revise these tutorials for Angular 2.0?

    Do you have any advice for developing an Angular 1.x wordpress theme to make it easy to port to 2.0?

    Thanks again,
    James

    • Hey James, I’m also quite new to AngularJS actually and not start to dive into 2.0 yet, but I’ll definitely rewrite the tutorials when the 2.0 is officially out.

      If you’re going to start a serious AngularJS app, I’ll say you’d better go with a standalone AngularJS app (+ WP API) rather than a WordPress theme (built with Angular) for the performance sake.

      You’ll find the AngularJS WordPress theme is not fast enough because it still makes extra queries that we might not need (that’s how WordPress works). With a pure, standalone Angular app, you can call the WP API without the general database queries from WordPress.

      I’m glad you find my work of use to you. Feel free to share more thoughts or comments with me. Thanks!

      • Hi Yoren,
        Thanks for the comment.

        As I am new to AngularJS, I am just trying to get my head around the comparison/process of developing between AngularJS WordPress Theme WP API vs AngularJS app (+ WP API). Does the later mean you are separating the two, i.e Build an Angular App and connect/call to your separate WordPress site w/ WP API ?

        I am trying to determine which way to develop. I am building a website for my company & plan to use a WP multi-site network (company has sub-brands/companies) that will use some of the same content and front-end template/component styleguide.

        Your feedback would be great 🙂

        • Hi Rohan,

          You’re right about these two approaches. I’ll say a standalone AngularJS app should outperform an AngularJS WordPress theme. (In any circumstance but especially for high volume websites.)

          For me I’m a PHP developer more than a JS developer so I go with the hybrid approach (AngularJS WordPress theme) that I can handle stuff much quicker. So it might depend on your technical background when considering to choose from them.

          I recommend that you check out the Angular WordPress seed project which can show you a different approach than mine. So you can have a better idea which one is easier for you.

          Contact me if you have any further question. Talk soon!

          • Hi Yoren,

            Thank you for your response!

            Would you say and AngularJS WordPress Theme would have better performance than a regular WordPress Site (w/out angular)?

            I do like the idea of having data available via api and spit out through routes/views and easily accessible.

            SEO is going to be a big factor as well, would you say the the permalink solution you have documented is sufficient and/or is their a need for crawlable js solutions like SEO.js / Prerender.io as well as WordPress SEO plugin by yoast?

            Thanks for your insights 🙂

          • Hey sorry about the delay, not sure why this comment was considered a spam.

            The AngularJS WordPress theme should generally have better performance than a regular WP theme. As you mentioned, this is a more MV* approach so the data and views won’t be mixed before they get to the client side.

            The permalink trick is good enough to direct search engines to the right place and get the right data. But I’m no SEO expert so can’t really tell how much the SEO.js or Prerender.io can boost the SEO performance. (They look promising just Google gets smarter every day…)

            There’s an interesting project from Michael Bromley https://github.com/michaelbromley/angular-social-demo shows how to make a Angular site more friendly to social sharing tools. Just FYI.

  • Hi, Great blog and intresting topic to explore.

    Can you just help to get out of this
    1) How can i use wordpress predefined functions within the template. Somehow i was able to make the templates a php template so that the php code runs into that but unable to use wp functions within template.

    2) How should i authenticate user for the theme so that he can able to login and comment for a post.

    • Hi, Manoj,

      1) Not sure why and how you’re doing this, so can’t help with it.
      2) Will be talking about creating a login form in our AngularJS and WordPress theme soon (hope I can make it this month)!

      • Hey there Yoren,

        I was wondering if you ended up writing the article about creating a login form with angular?

        • Hey Stefan, I didn’t spend too much time on updating this series in the past few months. Need to be focus on my own business at this time. Wish I could be back soon with more solid content. Happy learning AngularJS!

  • Hi,

    great resources 🙂

    What about if you use some plugins like https://yithemes.com/themes/plugins/yith-woocommerce-request-a-quote/
    The plugin extends the frontend of the WooCommerce Store with a button “Add to quote” that puts the product into a quote-cart you can send to the sellers backend (wp-admin)

    would you have to implement the logic to the API again too or can you use the give logic by the plugin somehow in your new API route? Is there a update safe, maintainable way or proposition to do it?

    • Hi Fabian,

      Unfortunately in most cases you can’t use such plugin with my AngularJS WordPress theme for most plugins hooking to filter like `the_content` which are not available in my theme.

      And of course we can still make use of the plugin by modifying the WP API or the WooCommerce API to include its functionalities. Just for now I can’t think of an easy way to accomplish such tasks.

  • Hi Chang!
    Really amazing job here!

    But look:
    – Category Slug [check]
    – Blog ID or Slug [check]
    – 404 [check]
    – Main and no dead links [check]
    – Custom Pages [Check]
    – Page ID or Slug [Not Working]
    – Tag Slug [Not Working]

    In my opinion :

    .when(‘/:slug’, {
    templateUrl: myLocalized.partials + ‘page.html’,
    controller: ‘Slug’
    })

    and use controller logic of “ContentCtrl”, or you think is better using always a virtual folder before? url: domain.com/page-id/ or domain.com/pages/page-id ?

    Thanks for your amazing work keep going!

  • Dear John! (haha)

    I do think that “prefixing” your route (the virtual folder method you mentioned) is the easiest way to get page and term slug both work in our theme.

    In fact, WordPress itself prefixes the permalink for posts, category, tags etc. by default. It doesn’t prefix page (I guess) because it assumes there won’t be a ton of pages in a single blog.

    Of course we can also make the controller guess which slug is requested (by adding some more if/else statements in the controller), but I prefer to make it simple and clear right from the start – prefixing the routes.

  • Hi Yoren.
    I want to say that your blog is really helpful for me. I was a little afraid to work with WordPress until I found your series of posts about AngularJS WordPress theme.
    I decided my future site to develop using wp api v2 and AngularJS but I have three important questions:
    1. How can I show any WordPress menus without php?
    2. Can I use in-place editing for logged in editors or at least redirect editor to wp admin editing page?
    3. Can I login users in wordpress with angularjs (I read your post about cookies auth but I don’t understood how to login)
    I”d be grateful for any help.

    • Yoren, do you know how to get categories by post and how to get categories with parent = 0 in wp rest api v2?

      PS: I read all of your posts. I’ll don’t be original if I’ll say that it’s really great series.
      Sorry for my english 🙂

    • Hi Sergey,

      Thanks for your kind words, here’re my responses to your questions:

      1. You can get the menu from WP API with this plugin: https://wordpress.org/plugins/wp-api-menus/. I haven’t tested but it looks promising.
      2. I haven’t integrated my AngularJS theme with any front-end editor, but displaying an “edit link” (to the admin dashboard) in a single post view should definitely work.
      3. My next post should be talking about how to create a login custom directive so we can log a user in at the front end. Stay tuned!
      4. Unfortunately, parent = 0 doesn’t seem to work with the terms endpoints. I’ll try to figure out how to hack the API, will share my findings with you if any.

      Cheers!

  • The wp api menus plugin has been updated to support v2 of the API by the way. New discovery endpoint is /wp-json/wp-api-menus/v2/menus.
    A lot of good stuff in here, working on making several small plugins based on all these posts.
    Great work Yoren!

    • Hey Tom, thanks for stopping by. Glad my posts can be of use to you. I’ll try WP API Menus since I got quite a few questions about building menus in a AngularJS theme.

  • Do you know how to get navigation menu from Rest API V2 ?
    I’ve tried an extension plugin called “WP REST API Menus”, didn’t work with V2!.
    So I tried to get it as a post type `nav_menu_item` and now I’m receiving 403 error from the server. any suggestions?

  • I wrote route for archive as below:
    .when(‘/:year’, {
    templateUrl: myLocalized.partials + ‘archive.html’,
    controller: ‘Archive’
    })
    .when(‘/:year/:month’, {
    templateUrl: myLocalized.partials + ‘archive.html’,
    controller: ‘Archive’
    })
    .when(‘/:year/:month/:day’, {
    templateUrl: myLocalized.partials + ‘archive.html’,
    controller: ‘Archive’
    })

    route params ‘/:year/:month’ and ‘/:year/:month/:day’ work exactly, but ‘/:year’ is conflicted with ‘/:slug’. what do you advise?

    • Hey Emil,

      As I’ve talked in some other posts, you’d better to prefix the routes or they’ll be against each other and all fallback to the default routes. (“/:slug” in my case)

      As long as you can prefix them and I believe you’re good to go! Cheers.

    • Hey Emil, thanks for reminding me that we need to rewrite the url for date archives in WordPress to make it consistent with our AngularJS app.

  • in function.php :

    function change_date_default_url() {
    global $wp_rewrite;
    $wp_rewrite->date_structure = ‘archive/%year%/%monthnum%/%day%’;
    $wp_rewrite->flush_rules();
    }
    add_action(‘init’, ‘change_date_default_url’, 1);

    script.js:

    .when(‘/archive/:year’, {
    templateUrl: myLocalized.partials + ‘archive.html’,
    controller: ‘Archive’
    })

    .when(‘/archive/:year/:month’, {
    templateUrl: myLocalized.partials + ‘archive.html’,
    controller: ‘Archive’
    })

    .when(‘/archive/:year/:month/:day’, {
    templateUrl: myLocalized.partials + ‘archive.html’,
    controller: ‘Archive’
    })

    all things work fine now .

    • Hey Andrea, thanks for stopping by. I was a bit worried that for the upgrading of WP API v2, the series of tuts has been outdated and may be confused new readers. If anything I could help before I get the posts updated to the current beta version of WP API v2, just let me know!

  • Your approach is very interesting. I’m Angular and WordPress developper and I never thought about using them together. I’m just wondering about SEO and crawler main problem when you create a website page with Angular.

  • Hi there,

    I have inherited a website from a developr that I believe used your method to build.
    Now I have read the intro, so I will skip the question why 🙂

    I have another question, client is complaining about the page being slow.
    It appears like browser is stuck for a few seconds before it loads.
    Would you mind pointing me what should I look for?

    The only thing I see in console is ‘WARNING: Tried to load angular more than once.”, everything else looks fine.

    And one suggestion if I may, and that is adding root to ‘myLocalized’ variable, like: myLocalized.root.
    Because I’m working on multisite install so ‘$http.get(myLocalized.root + ‘wp-json/pages/” would be proper url to make reqeust.

    Thanks in advanced

  • Hey,

    you have some really good tutorails here – thanks alot.
    I`m currently facing the issue. that a full angularjs page didnt
    read very well in google –
    Do you ever tried to use wordpress for a blog and
    a static angluar page for the navigation and static suff (on the same domain) `?
    What is your workflow with grunt /scss ?

    thanks and greets from germany
    Karl

    • Hey Karl, honestly I don’t have a workflow with grunt or gulp. I do use scss but not in a very automation way.

      I’m curious what do you mean by saying “a full angularjs page didnt
      read very well in google”? Do you mean that Google can’t index them?

      I haven’t hosted an Angular site myself, but I’ve read posts like this: http://www.centrical.com/test/google-json-ld-and-javascript-crawling-and-indexing-test.html and it shows SEO shouldn’t be a problem to JS apps.

      Thanks for your kind words. Looking forward to hearing back from you.

  • hi Yoren, thank for share, this is a very usefully, im try to adapt to our proyect in scsmathmexico.com.mx,

    from Mexico

    Edilberto R
    (Arjuna)

    • Hey Arjuna, that would be more than awesome! Wish you best luck on the project!

  • Hi YOREN

    is there any running example of WordPress back-end and angularjs front-end??
    Greets from Bangladesh.

    • Minhaz, managewp.org seems to use WP and AngularJS. Check if that’s what you’re looking for.

    • Hi Emil, You did an awesome job! Honestly I definitely learn more from you on how to deal the comment form. Really appreciate you share with me!

  • sorry, the code is not correctly displayed in the comment content ))))
    give me your email , I’ll send you code .

  • i use plugin WP REST API v2 . Because cache broswer, xxx/wp-json/wp/v2/posts/ don’t update realtime when i publish or update a post. Can you help me to solve this problem? Thanks

  • Hi Yoren nice tutorial, thanks man.

    I use ninja forms plugin but i try insert the shortcode in wp_localize_script function, but the ajax functionality don’t work. Which is the best practice to use shortcodes with Angularjs?

    This is the code:

    function angular_scripts() {

    wp_enqueue_script(
    ‘bundlejs’,
    get_stylesheet_directory_uri() . ‘/static/app.js’,
    array(),
    false,
    true
    );

    wp_localize_script(
    ‘bundlejs’,
    ‘localized’,
    array(
    ‘templateUrl’ => get_template_directory_uri(),
    ‘homeUrl’ => home_url(),
    ‘contactDateHome’ => do_shortcode( ‘[ninja_forms id=5]’ )
    )
    );

    }

    add_action( ‘wp_enqueue_scripts’, ‘angular_scripts’ );

    I apreciatte your help.

  • How integrate a contact form in Angular + WordPress theme. Plugin or other solutions?

    • Hi, it’s not my theme so can’t help you with it. Please contact the author.

  • Hi Yoren,

    I like your blog 1fix.io and I learned a lot from YOU, THANKS A LOT !!!
    (do u have a paypal for donations ?)

    I have a question about passing the data to $scope using a “var Globals” array that contains the name of current category and the list of posts.

    Like this website : view-source:phandroid.com/category/tips-tricks/

    In the code you can search “Globals” to see what I’m trying to achieve, I like this approach since it does speed the load of data on the page without using a separate http GET.

    I have read all the series including this article :
    https://1fix.io/blog/2014/11/05/angularjs-json-api-wp-theme/

    I think of getting WP REST to use a custom route and then format it into Javascript format but how???

    THANKS IN ADVANCE!

  • Hey Soufiane, sorry for the late reply. To me I’d say this doesn’t look like a common approach for most web applications. While you might save some GET calls, you also add too much unused data to each page, and they still cost loading time.

Submit a comment

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