1

I'm building out my first full production website with react and I've run into an issue with the WP REST API. I have a blog page which lists my posts from WordPress no problem. The only issue is, I map over the array of posts and the author is a number (author ID).

How can I fetch that users ID in this situation?

import React, { Component } from "react"
...
class Blog extends Component {

   static async getInitialProps() {

      const postsRes = await fetch(`${Config.apiUrl}/wp-json/wp/v2/posts?_embed`)

      const post = await postsRes.json()

      return(post)

   }

render() {
   const posts = this.props.posts.map((post,index) => {
   return(
      <li key={index}>
         {post.better_featured_image != null ? <Feat img= 
         {post.better_featured_image.source_url}/> : ""}
         <Link
          as={`/blog/${post.slug}`}
          href={`/blog?slug=${post.slug}&apiRoute=post`}
         >
         <a>{post.title.rendered}</a>
         <p>{post.author}</p> //Returns ID I need name
         </Link>
       </li>
    )
   })
}

}

I want to be able to put the authors name where I have the comment above. I've tried building functions and I just can't figure it out. I'm trying to figure out if I should call a function that could pass that id from post.author back and then append it to the /wp-json/wp/v2/users/Insert Here

Any hints or suggestions!

(Sorry if I have minor syntactical errors, I use styled components to I hand typed this with just standard jsx elements)

FreddieMixell
  • 300
  • 4
  • 15

2 Answers2

3

You have two options, First:

==> To fetch the user data through the endpoint:

/wp-json/wp/v2/users/USER_ID

==> The second option to register a new field author_name to the post response as follows:

add_action( 'rest_api_init', 'rest_get_author_name' );
function rest_get_author_name() {
    register_rest_field( 'post',
        'author_name',
        array(
            'get_callback'    => 'get_author_name'
        )
    );
}
function get_author_name( $object ) {
    return the_author_meta( 'user_nicename' , $object['author'] );
}

This code should be placed in functions.php in your theme.

Shahin
  • 535
  • 4
  • 10
2

Okay so for anyone looking at this in the future. The answer from Shahin is still correct but there is an easier way I discovered.

As you can see I'm using /wp-json/wp/v2/posts?_embed

Using _embed gives you some extra magic.

<p>Author: {post._embedded.author[0].name}</p>

This is how you would access the authors name. If you're looking for anything you should just check _embedded first because it was a breeze!

FreddieMixell
  • 300
  • 4
  • 15