Using Axios to Fetch WordPress Post Data from WP-JSON Rest API Endpoints in React

by | March 14, 2021 | Javascript, React, Website Development

This page may contain affiliate links to recommended products or services. If you choose to purchase after clicking a link, I may receive a commission at no additional cost to you.

Last updated on: February 7, 2023

So, you want to use Axios to fetch WordPress post data from WP-JSON REST API endpoints in react, huh?

Maybe you’re doing some WP theming or creating a front-end for a headless WordPress website and you want to pull in post data to display on the page. Whatever — cool.

Well, here’s one way to go about using React and Axios to fetch post data from your WordPress back-end, so you can render it on the front end.

Ingredients

You’ll need a few key ingredients to make this WordPress recipe work.

  • A WordPress site (i.e. a back-end with content)
  • ReactJS
  • Axios

Enabling Custom Post Types

By default, WordPress posts and pages are exposed to the WP Rest API, but if you want to access custom post types you’ll need to enable REST functionality when you register them.

Simply put, add 'show_in_rest' => true to your custom post type’s args.

add_action('init', function() {
    register_post_type('toaster', [
        'public' => true,
        'label' => 'Toasters',
        'show_in_rest' => true // <-- ADD THIS LINE
    ]);
});

Recipe

Here’s a ReactJS recipe for success. You can use the following to create a component that displays a post list.

class PostList extends Component {
  constructor(props) {
    super(props);
    this.state = {
      posts: []
    };
    this.createMarkup = this.createMarkup.bind();
  };
  componentDidMount() {
        axios.get("https://your-wordpress-site.com/wp-json/wp/v2/posts")
        .then(posts => {
            this.setState({
                posts: posts.data
            });
        });
  };
  createMarkup(html) {
    return { __html: html };
  };
  render() {
    return (
      <div>
        {this.state.posts.map(post => (
          <Link to={`/${post.slug}`} key={post.id}>
            <div className="card" key={post.id}>
              <div className="card-content">
                <h3 dangerouslySetInnerHTML={this.createMarkup(post.title.rendered)}></h3>
                <div
                  dangerouslySetInnerHTML={this.createMarkup(
                    post.excerpt.rendered
                  )}
                />
              </div>
            </div>
          </Link>
        ))}
      </div>
    );
  }
}
export default PostList;

Use this code snippet as a starting point to template the front end of your WordPress site.

The HTML markup and CSS styling can be done any way you want — what’s important here is that you’re using Axios and the WP-JSON Rest API to get post data to display in a ReactJS component.

Bonus: Enable WP Advanced Custom Fields REST API Endpoints

You can make fetching WordPress post data with Axios even more powerful by exposing your site’s Advanced Custom Fields field endpoints to the WP Rest API.

The simplest way is using the free WordPress plugin ACF to REST-API. After installing and activating this plugin, your ACF fields can be accessed similarly to the rest of your post’s data.

Floyd Hartford is a website developer from southern Maine. He's focused on creating and building WordPress websites and loves spending time digging into code like HTML, CSS, scss, jQuery, PHP, and MySQL.

0 Comments

Submit a Comment

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

three × four =

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

Looking for WordPress Help?

I’m a freelance web developer specializing in small business and corporate marketing websites.

Pin It on Pinterest