First we will need access to a Wordpress (obviously).

Let’s start a project with Express.

If you don’t have express-generator you can install with:

npm install express-generator -g

Create a new dir for the project:

mkdir node-wordpress
cd node-wordpress

Starting express generator with “hbs” (handlebars template engine) option:

express --hbs

Add node-wordpress library:

npm i --save wordpress

Install all dependences:

npm i

Start the project:

DEBUG=node-wordpress:* npm start

This is a sample of routes/index.js

var express = require('express');
var router = express.Router();

var wordpress = require( "wordpress" );
var client = wordpress.createClient({
    url: "http://mywwordpresssite.com",
    username: "myuser",
    password: "mypassword"
});


/* GET home page. */
router.get('/', function(req, res, next) {
  client.getPosts({ status: 'publish' }, function( err, posts ) {
		if (err) {
		   next(err);
		} else {
		   
		   for (var i = 0, len = posts.length; i < len; i++) {
		      console.log('title: '+posts[i].title);
		      console.log('status: '+posts[i].status);
		      console.log('-----------------------------------');
		    }
		   
	       res.render('index', { title: 'Express', posts: posts });
	    }
  });
  
});

module.exports = router;

And this is the hbs file /views/index.hbs

<h1>{{title}}</h2>
{{#each posts}}
  <h2>{{title}}</h2>
  <p>{{{content}}}</p>
{{/each}}

Go to http://localhost:3000 and see the result.

More information about handelbars template engine here.

Next week I’m going to write about how to use Memcached to improve this project.