What is Bootstrap WordPress APIs Mobile Apps

Build a mobile application using WordPress, Ionic and AngularJS

What you are going to create

introduction

In this tutorial I will explain step by step how to create a modern, hybrid, mobile application (iOS and Android) of your WordPress website using the latest technologies. We use Ionic Framework, ECMAScript 6, npm, Webpack and Apache Cordova.

At the end of this tutorial, you will get the following application. It only has three modules, a At home Module that shows your latest posts, a post Module that shows a specific contribution, and a Menu Module that displays the menu.

1. Tools

Ionic Framework

The beautiful open source front-end SDK for developing amazing mobile apps using web technologies.

The Ionic Framework ecosystem is huge, includingIonic CLI (Command line tool),Ionic push (simple push notifications) andIonic platform (Backend services). It is currently one of the top open source projects on GitHub with more than 19,000 stars and over 600,000 apps built.

Ionic covers all your application needs. However, in this tutorial, I'm only going to focus on the Ionic Framework (or Ionic SDK), which is a set of AngularJS directives (web components) and services.

ECMAScript 6 (ES6)

ECMAScript 2015 (6th Edition) is the current version of the standard for ECMAScript language specifications. ES6 was officially approved and published as a standard by the ECMA General Assembly on June 17, 2015.

ECMAScript 6 gives you access to many new features, many of which are inspired by CoffeeScript, such as: B. as arrow functions, generators, classes and to define expressions. Although ES6 was recently approved, you can now use it with a JavaScript compiler like Babel.

Node Package Manager (npm)

Node Package Manager is the most popular package manager in the world. The number of packages is growing faster than the combination of Ruby, Python and Java. npm runs on Node.js.

Why not Bower?

We choose npm because using Bower and npm in the same project is painful and supporting CommonJS with Bower is not easy. CommonJS defines a module format to resolve the JavaScript area outside of the browser, and npm supports this. CommonJS modules can be required with ES5 or ES6.

// ES5 var angle = required ('angle'); // ES6 import angle from "Winkel";

Webpack

In my opinion, Webpack has been a huge part of the industry in modifying complicated grunt or gulp scripts that you need to manage. With webpack you can request and forward any file type (.js, .coffee, .css, .scss, .png, .jpg, .svg, etc.) Loader generate static assets available for your application.

It differs from Grunt and Gulp in that most of your needs (minification and compilation) can be covered by adding a few configurations. You don't need to create scripts. For example, if you request a Sass file, compile it, auto-correct it, and paste the resulting flattened CSS into your application, it's easy:

test: /\.scss$/, loader: "style! css! autoprefixer! sass"

I don't think I need to show you the equivalent of Gulp or Grunt. I think you get my point.

2. Requirements

This tutorial assumes that you have:

  • Basic knowledge of AngularJS and Ionic
  • a WordPress website ready to be queried (a local install is fine)
  • a machine with Node.js, npm, Bower (we need it for some dependencies)
  • Git with write access with no installed Sudo in the project folder

3. Installation

Before we get started, there are two things you need to install:

  • a WordPress plugin that turns your blog into a RESTFUL API
  • the application itself

RESTFUL API

To get the posts for your WordPress installation, you need to install the WP REST API plugin. Make sure you install the version1.2.x version 2.x is on the way.

  1. In WordPress, go to Plugins> Add New.
  2. Search forWP-REST-API (WP-API).
  3. click Install now to install the plugin.
  4. If the installation is successful, click Activate plugin to activate it.

If the installation was successful, open a browser and enter http://example.com/wp-json. This should give you an answer similar to the one below.

"Name": "Lorem Ipsum-Blog", "Description": "Just one more WordPress site", "URL": "http://YourDomainName.com/wp-json", "Routes":, "Authentication" :, "meta":

application

To install the application, clone the repository using the commands below.

# Clone the repository and give it a name (here myTutorial) $ git Clone https://github.com/tutsplus/Hybrid-WordPressIonicAngularJS.git myTutorial # Open the project $ cd myTutorial

Next, you'll create a configuration file and install the dependencies.

# Copy the standard configuration into your personal configuration file $ cp config / default.config.json config / config.json # Install the dependencies $ npm install

Open to make sure both the application and the REST API are working togetherconfig / config.json. This is your personal configuration file that Git will ignore. Change that Base url from the API to the one for your WordPress installation.

"api": "baseUrl": "http://yourDomainName.com/wp-json"

Run and open http: // localhost: 8080 / webpack-dev-server / in a browser. If everything works as expected, you should be in front of a running application displaying your WordPress posts. I've created a demo application that will give you an idea of ​​what to expect.

Now that you can see the result of what we are striving for, let me go through the details. Notice that the following code examples are simplified. You can find the source code on GitHub.

4. Dependencies

The command installs multiple libraries. Some of them are direct dependencies while the rest are development dependencies.

Direct dependencies

The direct dependencies are dependencies that your application needs to run properly when it is built.

"Dependencies": "ionic-sdk": "^ 1.0.0", "wp-api-anglejs": "^ 1.0.0"

Note that the application does not depend on AngularJS directly as ionic-sdk already includes angle.js, angle-animate.js, angle-sanitize.js, and angle-ui-router.js.

wp-api-anglejs (WordPress WP API Client for AngularJS) is a set of AngularJS services that allow communication with the previously installed REST API plugin. You can see the full list of dependencies on GitHub.

Development dependencies

Development dependencies are mostly webpack loaders. Loaders are functions that take the source of a resource file, make some changes, and return the new source. We need loaders that handle .scss, .js (ES6), .html and .json. You can see a full list of development dependencies on GitHub.

5. Application architecture

I have been developing AngularJS applications for a long time and after much experimentation, I have committed myself to the following architecture:

  • a file that can be edited live under or folder
  • Every AngularJS module needs a correct folder
  • each module file must define a unique namespace (and be the only place that namespace appears)
  • each module file must declare all of its dependencies (even if dependencies have already been inserted into the app)
  • each module file you need to declare all of its configurations, controllers, services, filters, and so on.
  • Every configuration, every controller, service, filter etc. has to export a function (CommonJS).
  • If a module needs a certain style, the .scss file must live within the module

These recommendations are powerful because they ensure that you have loosely coupled modules that can be shared by multiple applications without causing problems.

This is what the structure of the application folders looks like:

lib / ├── menu / └──. menu.module.js .html menu.html ├── home / │ └── home.module.js └── home.config.js home.controller.js └── └── home.html ├── post / └── └── post.module.js └── └── post.config.js post.controller.js └── post. Html ├── scss / └── _variables.scss └── bootstrap. scss ├── index.js ├── index.html

Entry point

An entry point is required when using Webpack. Our entry point is lib / index.js. It contains the basic dependencies of our application (e.g.ionic.bundle that includes AngularJS), our homemade modules, and adds the Sass entry point.

// Ionic, Angular and WP-API client import 'ionic-sdk / release / js / ionic.bundle'; import 'wp-api-anglejs / dist / wp-api-anglejs.bundle'; // Our modules import modhome from './home/home.module.js'; import modPost from './post/post.module.js'; import modMenu from './menu/menu.module.js'; // style entry point import './scss/bootstrap';

Now that we have imported our dependencies, we can create our application module. Let's call our app prototype. It has, and our homemade modules as dependencies.

// Create our prototype module let mod = angle.module ('prototype', ['ionic', 'wp-api-anglejs', modHome, modMenu, modPost]);

Once the module is created we can export it as a standard CommonJS module.

export standard mod = mod.name;

This is a great example of what an AngularJS module should look like.

Routing


Our application has a side menu in which the Menu Module is being rendered. It also has a content area where the At home and post Modules are displayed.

The directive is part of the UI router used by Ionic. It tells (UI router service) where to put your templates. Likewise, the directive appended to is a custom Ionic directive that is used below. You can consider both statements to be identical.

Here is a simplified version of the state, the state that all modules have in common:

Export standard function ($ stateProvider) 'ngInject'; return $ stateProvider.state ('root', abstract: true, views: '@': template: '');

For more information on named views, see the GitHub documentation.

Menu module

lib / ├── menu / └── └── menu.module.js │ └── menu.html

The Menu Module is very simple. Its purpose is to add a menu in it. Without this module the side menu would be empty. The menu module only declares a configuration file that it has and as dependencies.

import modConfig from './menu.config'; let mod = angle.module ('prototype.menu', ['ionic', 'ui.router']); mod.config (modConfig); export standard mod = mod.name;

The most interesting part is the configuration. We don't want to create a status for the menu module as it is available everywhere. Instead, we decorate the state with the menu content. With the state to be defined in the, we must use to refer to it.

Export standard function ($ stateProvider) 'ngInject'; $ stateProvider.decorator ('views', (state, parent) => let views = parent (state); if (state.name === 'root') views ['menu @ root'] = template: required (" ./ menu.html "); return view;);

Main module

lib / ├── home / │ └── home.module.js └── └── home.config.js └── home.controller.js home.html

home.module.js

The At home Module shows the latest posts from your WordPress website. It has a configuration file, a controller and depends on the following libraries:

    import modConfig from './home.config'; import modController from './home.controller'; let mod = angle.module ("prototype.home", ["ionic", "ui.router", "wp-api-anglejs"]); mod.config (modConfig); mod.controller ('HomeController', modController); export standard mod = mod.name

    home.config.js

    The configuration adds a new status, with the URL with a template and a controller (both within the module).

    Export standard function ($ stateProvider) 'ngInject'; $ stateProvider.state ('root.home', url: "/ home", views: 'content @ root': template: required ("./ home.html"), controller: "HomeController as homeCtrl");

    home.controller.js

    This is a simplified version of the home controller logic. It contains two functions:

    • : This function is filled out. It uses the service that is part of the wp-api-anglejs Library.
    • : This function removes posts and calls again.
    Export standard function ($ scope, $ log, $ q, $ wpApiPosts) 'ngInject'; var vm = this; vm.posts = []; vm.loadMore = loadMore; vm.refresh = refresh; Function refresh () vm.posts = null; loadMore (). finally (()) => $ scope. $ broadcast ('scroll.refreshComplete')); function loadMore () return $ wpApiPosts. $ getList (). then ((answer) => vm.posts = (vm.posts)? vm.posts.concat (response.data): response.data; $ scope. $ broadcast ('scroll.infiniteScrollComplete'););

    home.html

    The template has an instruction that allows users to reload the page by pulling down the page. It also has a directive that calls this function when achieved. Posts are displayed with policy.

    Top: Use the phrase for better performance. It minimizes DOM manipulation when a post is updated.

    Post module

    lib / ├── post / └── j post.module.js └── cont post.config.js └── └── post.controller.js └── post.html

    The post Module only shows one post. It has a configuration file, a controller and depends on the same librairies as the At home Module.

    post.module.js

    import modConfig from './post.config'; import modController from './post.controller'; let mod = angle.module ('prototype.post', ['ionic', 'ui.router', 'wp-api-anglejs']); mod.config (modConfig); mod.controller ('PostController', modController); export standard mod = mod.name

    Similar to the home module, the configuration adds a new status,, with the URL. It also registers a view and a control.

    post.config.js

    Export standard function ($ stateProvider) 'ngInject'; $ stateProvider.state ('root.post', url: "/ post /: id", views: 'content @ root': template: required ("./post.html")), controller: "PostController as postCtrl" );

    post.controller.js

    The controller retrieves the contribution specified in the URL via the service (UI router service).

    Export standard function ($ scope, $ log, $ wpApiPosts, $ stateParams) 'ngInject'; var vm = this; vm.post = null; $ scope. $ on ('$ ionicView.loaded', init); function init () $ wpApiPosts. $ get ($ stateParams.id) .then ((response) => vm.post = response.data;);

    post.html

    The template has an instruction that indicates a loader while the data is being fetched from the WordPress REST API. When the post is loaded, we use an Ionic map to represent the author's avatar, post title, and post content.

    top: Use the expression,, (introduced in Angular 1.3) to avoid looking at data that does not change over time.

    Style (sass)

    lib / ├── scss / └── _Variablen.scss └── └── bootstrap.scss

    The file we imported into our entry point is as simple as this:

    @import "./variables"; @import "~ ionic-sdk / scss / ionic";

    First we import our variables. We then import the Ionic styles. If you import our variables before Ionic, you can override the Sass variables specified by Ionic.

    For example, if that's what you want positive Color instead of red instead of blue, you can override it like this:

    $ positive: red! default;

    6. Android and iOS

    installation

    Run the following commands in the project folder and select the platform you want to create a platform for.

    $ cp config.dist.xml config.xml $ npm run run installCordova Which platforms do you want to create? (android ios):

    In addition to installing platforms within the folders, the script installs a plugin. For the demo we need the plugin. It is required that the application can query the previously created WordPress REST API.

    When you open config.xmlYou will see that we allow access to any type of origin (). This is of course for demonstration purposes only. If you are deploying your application to production, make sure to restrict access as follows:

    Android

    requirements

    Run the command is short for. This removes everything within the www Folder, creates a non-scaled version of the app and runs the command. If an Android device is connected (run to be sure, the command will load the app onto the device; otherwise, it will use the Android emulator.

    # Run Android $ npm and run runAndroid

    iOS

    requirements

    If you don't have an Apple device, you should install the iOS simulator. It's really good and better than the Android emulator.

    $ sudo npm install -g ios-sim

    Running is short for. The command is an abbreviation for.

    # Run iOS $ npm and run runIosEmulator. $ Npm Run runIosDevice

    Conclusion

    With this tutorial, I tried to show you how easy it is to build a mobile, mobile application for your WordPress website. You should now be able to:

    • Create loosely coupled modules that respect CommonJS specifications
    • Import of CommonJS modules with ECMAScript 6
    • Use the WordPress REST API client side (with wp-api-anglejs).
    • Leverage the Ionic Framework to create a great user interface
    • Use Webpack to bundle your application
    • Use Cordova to run the application on iOS and Android

    If you want to go further, take a look at a project I created a few months ago, the WordPress Hybrid Client.

    WordPress Hybrid Client

    WordPress Hybrid Client (WPHC) is an open source project available on GitHub that allows you to create iOS and Android versions of your WordPress website for free. WPHC is based on the same technology stack that we used in this tutorial.

    WPHC includes the following features:

    • announcements
    • Bookmarks (offline mode)
    • Google Analytics support
    • automatic content updates
    • social buttons
    • Accessibility (Post font size)
    • multiple languages ​​(English, French, Chinese)
    • infinite scroll
    • Syntax highlighter for tech blogs
    • Image caching
    • App rating