Accessing and Displaying WordPress Blog using WordPress REST API

I had the template of my React website built and I wanted to pull data from my WordPress two blogs into my website.  In order to have all of this information in one place, I wanted access to the data from both blogs (my travel blog and my technical blog), preferably in JSON.

In my original React template, I was making Ajax requests to my own server.  However, since I now wanted to pull data from WordPress, I adjusted my Ajax request’s URL to be a URL corresponding to the WordPress REST API instead of a URL defined in my Server.js.  Here is the Ajax Request:

$.ajax({
            url: 'https://public-api.wordpress.com/rest/v1.1/sites/mysquarecm.wordpress.com/posts”,
            dataType: 'json',
            cache: false,
        })
         .done(function(result){
             this.setState({data: result});
         }.bind(this))
         .fail(function(xhr, status, errorThrown) {
             console.error(this.props.url, status, errorThrown.toString());
         }.bind(this));   

Mysquarecm.wordpress.com is the name of my website and I added /posts as my parameter because I wanted to pull all the posts from my blog, by default the WordPress API will return up to 20 posts if you do not specify the number of posts to return.

If successful, I am setting the state of data to result (the JSON data returned from the API call).  Otherwise, I am logging an error in the console.

Now, data is storing all of my JSON data and I must Parse this data in order to display it on my React webpage.

In order to do this, I will parse through all of the posts using the Javascript map function and maps each post to a formatted Blog Post.  It stores these formatted posts in the variable memberNodes and then embeds and then returns the memberNodes along with additional formatting.

The code that does this:

render: function() {
        if (this.state.data.posts){
            var memberNodes = this.state.data.posts.map(function(post) {
                return (
                    <Blog>
                    title = {post.title}
                    content = {post.content}
                    URL = {post.URL}
                    </Blog>
                    );
                });
            }

            return (
            <div>
            <div>  
            <div className = {style.blogContent}>          
            {memberNodes}
            </div>
            </div>
            <button type="submit" onClick={this.handleSubmit}>Load More </button>
            </div>
            );
        }

The Blog Component that formats the blog data it receives from the code above (since this uses dangerouslySetInnerHtml only use if server code is from trustworthy source!) :

module.exports = React.createClass({
    render: function() {
        return (
        	  
              <div dangerouslySetInnerHTML={{__html: '<h1>' + this.props.children[1] + '</h1>' + this.props.children[3] 
              + '<a title=\"Zhong Lane\" href=' + this.props.children[5] + ' target=\"_blank\">Comment on this post. </a></p>\n<p style=\"text-align:left;\">'
              +  '</br>' }} />

        );
    }
});

To view the whole project, you can visit https://github.com/lac26/mywebsite.

To summarize, I made a call to the Wodpress API, received JSON data, formatted the JSON post data via the Javascript map function using another component titled Blog, stored the formatted post data in a variable memberNodes, and then embedded memberNodes directly into my HTML.

You can view documentation for additional parameters for WordPress Developers API at the official site: https://developer.wordpress.com/docs/api/.  It has documentation for receiving a specified number of posts, how to load comments related to a post, how to get a post by ID etc.

Thank you for reading, feel free to comment below!

Advertisements

Opening Sublime from the Command Line for Windows

This is a quick step-by-step tutorial going over how to install Sublime in Windows so that, when you type subl in the command line, it will open the Sublime Text Editor.

In order to be able to open Sublime from the command line, Sublime Text must first be installed in your system.  You can install the latest version of Sublime text here:

https://www.sublimetext.com/download

(Don’t know if you are using Windows 32 bit or 64 bit?  Look in Start -> Computer (This PC) -> Right Click Properties, look for the Operating System under System Type.)

Now, it is time to add the path to the Sublime install to your system variables.  This will allow you to access Sublime directly from the command line.

In order to do this:

  • Go to System -> Advanced System Settings -> Environment Variables
  • Go to System Variables -> Path and to the end of path (if you have existing variables in your path, don’t forget to insert a ; first) add the location you downloaded Sublime Text to.

For example, I downloaded Sublime Text 3 and the location I downloaded it to is C:\Program Files (x86)\Sublime Text 3.

Therefore, to the end of my PATH variable under System Variables I added ;C:\Program Files (x86)\Sublime Text 3.

You might have to restart your system for it to work.

To test, type subl into the command line.  Sublime text should open.  If it doesn’t, feel free to comment here!