Create Dynamic posts page by using Nest.js (SSG) and WP API

Next.js has been supported SSG Mode from version 9.3. Next-gen Static Site Generation (SSG) Support: Built-in […]

広告ここから
広告ここまで

目次

    Next.js has been supported SSG Mode from version 9.3.

    Next-gen Static Site Generation (SSG) Support: Built-in optimized static generation through new data fetching methods.

    https://nextjs.org/blog/next-9-3#next-gen-static-site-generation-ssg-support

    We can create static blog more easily.

    Setup

    Create React application by using create-next-app

    $ npx create-next-app example-wp-app
    $ cd example-wp-app

    Install WP API Client

    $ yarn add wpapi

    Then, your application directory is the following.

    % tree -L 2 -I node_modules 
    .
    ├── README.md
    ├── package.json
    ├── pages
    │   └── index.js
    ├── public
    │   ├── favicon.ico
    │   └── zeit.svg
    └── yarn.lock

    Create dynamic post page from SSG mode

    We can create dynamic page using [PARAM].js file.

    $ touch pages/posts/[id].js
    -> https://example.com/posts/765432 (Post ID)
    
    $ touch pages/[slug].js
    -> https://example.com/YOUR-POST-SLUG

    And we can handle your blog posts URL by using getStaticPaths method.

    $ code pages/[slug].js
    import Link from 'next/link'
    import WP from 'wpapi'
    
    const wpClient = new WP({
      endpoint: 'https://YOUR_WORDPRESS_SITE/wp-json'
    })
    
    /**
     * Create posts URLs
     **/
    export const getStaticPaths = async () => {
        const posts = await wpClient.posts()
        return {
            paths: posts.map(post => ({
                params: {
                    slug: post.slug
                }
            })),
            fallback: false
        }
    }
    
    /**
     * Render content
     **/
    export default () => {
        return (
            <div>
                <h1>Hello</h1>
                <Link href="/">Back</Link>
            </div>
        )
    }

    Import Dynamic blog posts from getStaticProps

    You can get the current page slug or id or any parameters in getStaticProps function.

    The example will get your WordPress posts by using the URL slug.

    
    export const getStaticProps = async ({params}) => {
        const posts = await wpClient.posts().slug(params.slug as string)
        return {
            props: {
                post: posts[0]
            }
        }
    }

    Create list of posts on the top page

    Finnaly, open pages/index.js to import and show your wp posts.

    import Head from 'next/head'
    import Link from 'next/link'
    import WP from 'wpapi'
    
    const wpClient = new WP({
      endpoint: 'https://YOUR_WORDPRESS_SITE/wp-json'
    })
    
    const Home = (props) => {
      return (
      <div className="container">
        <Head>
          <title>Create Next App</title>
          <link rel="icon" href="/favicon.ico" />
        </Head>
    
        <main>
          <h1 className="title">
            Welcome to <a href="https://nextjs.org">Next.js!</a>
          </h1>
          <ul>
            {props.posts.map(post => (
              <li key={post.id}>
                <Link href={post.slug}>
                  {post.slug}
                </Link>
              </li>
            ))}
          </ul>
        </main>
      </div>
    )
        }
    
    export const getStaticProps: GetStaticProps = async () => {
      const data = await wpClient.posts()
      return {
        props: {
          posts: data
        }
      }
    }
    
    export default Home
    

    Appendix: full example of pages/[slug].js

    import Link from 'next/link'
    import WP from 'wpapi'
    
    const wpClient = new WP({
      endpoint: 'https://YOUR_WORDPRESS_SITE/wp-json'
    })
    
    export const getStaticPaths = async () => {
        const posts = await wpClient.posts()
        return {
            paths: posts.map(post => ({
                params: {
                    slug: post.slug
                }
            })),
            fallback: false
        }
    }
    
    export const getStaticProps = async ({params}) => {
        const posts = await wpClient.posts().slug(params.slug as string)
        return {
            props: {
                post: posts[0]
            }
        }
    }
    
    export default ({post}) => {
        return (
            <div>
                <h1>Hello</h1>
                <h2>{post.title.rendered}</h2>
                {post.slug}
                <Link href="/">Back</Link>
            </div>
        )
    }

    広告ここから
    広告ここまで

    Random posts

    Home
    Search
    Bookmark