How to Use WordPress as a Headless CMS for Next.js

Understanding Headless WordPress

Headless WordPress refers to using only the back-end functionality of WordPress (managing and storing content) and using a separate system (such as Next.js) to display the front-end.

The benefit of this development model is that you can continue to use the powerful and easy-to-use content management tools of WordPress, while enjoying the advantages of modern front-end technologies such as Next.js, such as faster page loads (via server-side rendering or static site generation), a better user experience, and more flexible customization.

图片[1]-如何使用 WordPress 作为 Next.js 的无头 CMS-光子波动网 | 专业WordPress修复服务,全球范围,快速响应

Setting up the Next.js environment

Next.js helps developers easily build web applications, improving performance and optimizing the development experience. One of its main features is file-based routing, which simplifies the creation of routes.

Next.js is also very performance-oriented, providing features such as automatic code splitting to load only the JavaScript needed for each page, thus greatly reducing load times. To create a Next.js project, you can run the following command and use its default response:

npx create-next-app@latest nextjs-wp-demo

Learn about the program

Next.js 13 introducesApplication Router, replacing the existing pages directory for routing. Routing with App Router also requires creating folders in the app directory. A page.js file is then nested in the appropriate folder to define the route. In this project, app is the core directory to interact with and has the following file structure.

/
|- /app
    |-- /blog
        |-- /[postId]
        |-- page.js
        |-- page.js
    |-- globals.css
    |-- layout.js
    |-- navbar.js
    |-- page.js

We created three pages: the home page for basic information, the blog page for all posts in the WordPress CMS, and the dynamic page ([postId]/page.js) is used to display individual posts. Also note that navbar.js component, which is imported into the layout.js file to create a layout for the project.

图片[2]-如何使用 WordPress 作为 Next.js 的无头 CMS-光子波动网 | 专业WordPress修复服务,全球范围,快速响应

Getting Data from WordPress to Next.js

Using the WordPress REST API, posts, pages, and custom post types can be fetched by sending HTTP requests to specific endpoints. In theblog/page.js file to issue a fetch request for all posts in the WordPress CMS, and then finally issue a request to dynamically fetch the posts based on the parameters passed to theblog/[postId]/page.jsidEvery post in the.

It is a good idea to add the JSON API address to an environment variable before making these requests. This approach ensures that the base API URL is easily configurable and not hard-coded across multiple files.

 In the root directory of your Next.js project, create a.env file and add the following:

NEXT_PUBLIC_WORDPRESS_API_URL=https://yoursite.kinsta.cloud/wp-json/wp/v2

Make sure to replace the URL with the site's JSON API. additionally, add the.envuntil (a time).gitignore file so that it doesn't push the file to the Git provider.

图片[3]-如何使用 WordPress 作为 Next.js 的无头 CMS-光子波动网 | 专业WordPress修复服务,全球范围,快速响应

Get all posts from WordPress to Next.js

To get all posts from a WordPress site, add a new post to the blog/page.js file to create an asynchronous function called getPosts. This function uses the Fetch API to make a GET request to the /posts endpoint of the WordPress REST API.

async function getPosts() {
    const response = await fetch(
        `${process.env.NEXT_PUBLIC_WORDPRESS_API_URL}/posts`
    );
    const posts = await response.json();
    return posts; }
}

Upon receiving the response, it converts the response to JSON format and creates an array of post objects. These posts can be rendered in a Next.js application, providing a dynamic list of blog posts directly from WordPress.

const BlogPage = async () => {
    const posts = await getPosts();
    return (
        <div classname="blog-page">
            <h2>All Blog Posts</h2>
            <p>All blog posts are fetched from WordPress via the WP REST API.</p>
            <div classname="posts">
                {posts.map((post) =&gt; {
                    return (
                        <link href="{`/blog/${post.id}`}" classname="post" key="{post.id}">
                            <h3>{post.title.rendered}</h3>
                            <p
                                dangerouslysetinnerhtml="{{" __html: post.excerpt.rendered }}
></p>
                        </Link>
                    );
                })}
            </div>
        </div>
    );
};

In the Next.js page component, getPosts is called asynchronously to retrieve posts. Then, map the array of posts and render the title and excerpt of each post in the component.

This not only displays the posts, but also encapsulates each post in a link that navigates to a detailed view of the post. This is accomplished by using Next.js file-based routing, where the post ID is used to dynamically generate the URL path.

图片[4]-如何使用 WordPress 作为 Next.js 的无头 CMS-光子波动网 | 专业WordPress修复服务,全球范围,快速响应

Getting Dynamic Posts from WordPress to Next.js

In the code above, each post is wrapped in a link that helps the user navigate to the post's detail view. For individual post pages, you can utilize dynamic routing in Next.js to create a page that crawls and displays individual posts based on the post ID. A dynamic page [postID]/page.js has been created in the stater-files code.

Create a getSinglePost function similar to getPosts that gets a single post using the post ID passed as a parameter.

async function getSinglePost(postId) {
    const response = await fetch(
        `${process.env.NEXT_PUBLIC_WORDPRESS_API_URL}/posts/${postId}`
    );
    const post = await response.json();
    const post = await response.json(); return post; }
}

In the Dynamic Pages component, you can extract the post ID from the URL parameter, call getSinglePost with this ID, and then render the post content.

const page = async ({ params }) => {
    const post = await getSinglePost(params.postId);
    // ... the rest of the page code
}; }

The page can then be populated with the acquired data:

const page = async ({ params }) =&gt; {
    const post = await getSinglePost(params.postId);
    if (!post) {
        return <div>Loading...</div>;)
    }
    return (
        <div classname="single-blog-page">
            <h2>{post.title.rendered}</h2>
            <div classname="blog-post">
                <p> dangerouslySetInnerHTML={{ __html: post.content.rendered }}&gt;</p>
            </div>
        </div>
    );
};

summarize

Learn how to dynamically fetch and display posts in a Next.js project with headless WordPress. This approach seamlessly integrates WordPress content into Next.js applications, providing a modern and dynamic web experience. The potential of the Headless CMS API is not limited to posts; it also allows for retrieving and managing pages, comments, media, and more.


Contact Us
Can't read the article? Contact us for free answers! Free help for personal, small business sites!
Tel: 020-2206-9892
QQ咨询:1025174874
(iii) E-mail: info@361sale.com
Working hours: Monday to Friday, 9:30-18:30, holidays off
© Reprint statement
This article was written by Harry
THE END
If you like it, support it.
kudos0 share (joys, benefits, privileges etc) with others
commentaries sofa-buying

Please log in to post a comment

    No comments