How to Limit Post Count and Fetch Custom Fields with WordPress REST API

0

In this article, we will explore how to use the WordPress REST API to fetch custom fields and limit the number of posts. We’ll dive into how to efficiently manage data through the REST API and use it with frontend frameworks like React and Next.js.

We’ll focus on two key tasks:

  • Limit Post Count: How to limit the number of posts fetched at once using the `per_page` parameter.
  • Fetch Custom Fields: How to include WordPress custom fields (e.g., `set_lang`) in the REST API response.

By the end of this article, you’ll have a solid understanding of [API usage] and [how to work with WordPress custom fields].

Limiting the Number of Posts with WordPress API

It’s essential to prevent loading an excessive number of posts through the REST API and to fetch only the desired amount. You can easily control this by using the `per_page` parameter. By default, the API returns 10 posts at a time, but you can adjust this value based on your needs.

API Request Example

Here’s an example where we fetch only 5 posts at a time:

async function fetchPosts() {
  const res = await fetch('https://example.com/wp-json/wp/v2/posts?per_page=5');
  if (!res.ok) {
    throw new Error('Failed to fetch posts');
  }
  return res.json();
}

In this example, we added `?per_page=5` to the API call to return a maximum of 5 posts. It’s simple but highly effective. This can significantly improve [web page performance].

Fetching Custom Fields: `set_lang` Field

By default, WordPress doesn’t include custom fields in the REST API response, but the solution to this is quite simple. You can either use the Advanced Custom Fields (ACF) plugin in WordPress or modify the `functions.php` file of your theme to achieve this.

Using the ACF Plugin

Once ACF is installed and the `set_lang` field is added, here’s how to include this field in the API:

// Code to add to functions.php
function add_custom_fields_to_rest_api( $data, $post, $context ) {
    // Fetch custom field value
    $custom_field = get_post_meta( $post->ID, 'set_lang', true );
    
    // Add field to API response
    $data->data['set_lang'] = $custom_field;

    return $data;
}

// Include custom field in API call
add_filter( 'rest_prepare_post', 'add_custom_fields_to_rest_api', 10, 3 );

By using the above code, the custom field `set_lang` will be included in the WordPress REST API response. This allows you to fetch the necessary data and process it on the frontend.

Using API Data with React and Next.js

Now, let’s look at how to fetch this API data and use it in React and Next.js. We’ll display the list of posts along with their custom fields.

async function fetchPosts() {
  const res = await fetch('https://example.com/wp-json/wp/v2/posts?per_page=5');
  if (!res.ok) {
    throw new Error('Failed to fetch posts');
  }
  return res.json();
}

export default async function Home() {
  const posts = await fetchPosts();

  return (
    <div>
      <main>
        <h1>Latest WordPress Posts</h1>
        <ul>
          {posts.map((post: any) => (
            <li key={post.id}>
              <h2>{post.title.rendered}</h2>
              <p>Language: {post.set_lang || 'N/A'}</p> {/* Custom field value used */}
              <div dangerouslySetInnerHTML={{ __html: post.excerpt.rendered }} />
            </li>
          ))}
        </ul>
      </main>
    </div>
  );
}

In this code, we use `post.set_lang` to render the custom field value. This allows you to easily display language information for each post. The combination of React and WordPress API is incredibly powerful, allowing you to implement dynamic content with custom fields seamlessly.

Conclusion

The WordPress REST API is a very useful tool. By learning how to fetch custom fields and limit the number of posts, you can optimize API performance and provide a better user experience on the frontend.

The insights gained from this article can help you enhance the efficiency of your WordPress site and improve user experience.

Leave a Reply