Search code examples
wordpressreactjsheadlessnext.jswp-api

Fetching User Data From ID: WP REST API


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)


Solution

  • 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.