Headless WordPress Blog with Next.js: Simplified Setup
medium.com

Headless WordPress Blog with Next.js: Simplified Setup

This guide gets you started with a streamlined Headless WordPress blog powered by Next.js. Keep writing amazing content, and Next.js handles the dynamic frontend.

Prerequisites:

  • Basic understanding of JavaScript, React, and Next.js
  • A WordPress site with the WPGraphQL plugin (https://www.wpgraphql.com/)
  • Node.js and npm (or yarn) installed

Steps (Simplified):

  1. Create Next.js Project:

npx create-next-app my-headless-blog
cd my-headless-blog        

2. Install Dependencies:

npm install apollo-client graphql        

3. Connect to WordPress API:

  • Create a .env.local file (ignored in version control) at the project root.
  • Add this line, replacing the URL with your WordPress site's:

NEXT_PUBLIC_WORDPRESS_API_URL=YOUR_WORDPRESS_SITE_URL/graphql        

4. Fetch and Display Posts:

  • We'll combine fetching and display for this simplified version.
  • Create a Home.js page component to handle everything:

import React from 'react';
import gql from 'graphql-tag';
import { ApolloClient, InMemoryCache, HttpLink } from '@apollo/client';

const GET_POSTS = gql`
  query GetPosts {
    posts(where: { status: PUBLISHED }) {
      edges {
        node {
          title
          content
          featuredImage {
            sourceUrl
          }
        }
      }
    }
  }
`;

const wordpressApiUrl = process.env.NEXT_PUBLIC_WORDPRESS_API_URL;

const client = new ApolloClient({
  link: new HttpLink({ uri: wordpressApiUrl }),
  cache: new InMemoryCache(),
});

const Home = async () => {
  const { data } = await client.query({ query: GET_POSTS });
  const posts = data.posts.edges.map(({ node }) => node);

  return (
    <div>
      <h1>My Headless WordPress Blog</h1>
      <ul>
        {posts.map((post) => (
          <li key={post.id}>
            <h3>{post.title}</h3>
            <p>{post.content}</p>
          </li>
        ))}
      </ul>
    </div>
  );
};

export default Home;        

Remember: This is a streamlined example. You can add further features like:

  • Styling (CSS frameworks or custom styles)
  • Routing for individual posts
  • Images and other media handling

With this setup, your WordPress content automatically updates your Next.js blog!

要查看或添加评论,请登录

社区洞察

其他会员也浏览了