项目作者: gregrickaby

项目描述 :
NextJS + WordPress Starter
高级语言: JavaScript
项目地址: git://github.com/gregrickaby/nextjs-wordpress.git
创建时间: 2020-04-04T00:55:19Z
项目社区:https://github.com/gregrickaby/nextjs-wordpress

开源协议:

下载


Next.js + WordPress

It’s headless WordPress! 💀 - https://nextjswp.com

This is a bare-bones Next.js app, which fetches data from WordPress via WPGraphQL and styles it with TailwindCSS.

Please consider it a starting point for your next headless WordPress project.


Supported Features

  • Category and Tag Archives
  • Comments
  • Custom Fields
  • Custom Post Types
  • On-demand Revalidation
  • Post/Page Previews
  • RSS Feed
  • Robots.txt
  • Search
  • Sitemap.xml
  • Static Site Generation (SSG)
  • TypeScript, ESLint, and Prettier
  • WordPress Menus
  • Yoast SEO

Plus it’s really, really fast! 🚀

screenshot


Setup

1. Clone the repo

  1. git clone git@github.com:gregrickaby/nextjs-wordpress.git

2. Install dependencies

  1. npm i

3. Create a .env.local file

  1. cp .env.example .env.local

Customize the URLs in .env.local to match your WordPress setup:

  1. # WordPress GraphQL API URL. No trailing slash.
  2. NEXT_PUBLIC_WORDPRESS_GRAPHQL_URL="https://blog.nextjswp.com/graphql"
  3. # WordPress REST API URL. No trailing slash.
  4. NEXT_PUBLIC_WORDPRESS_REST_API_URL="https://blog.nextjswp.com/wp-json/wp/v2"
  5. # Optional. JWT auth refresh token.
  6. #NEXTJS_AUTH_REFRESH_TOKEN=""
  7. # Preview Secret. Must match the constant in wp-config.php.
  8. NEXTJS_PREVIEW_SECRET="preview"
  9. # Revalidation Secret. Must match the constant in wp-config.php.
  10. NEXTJS_REVALIDATION_SECRET="revalidate"

4. Configure next.config.js

Update the URL in next.config.js to match your WordPress site:

  1. const nextConfig = {
  2. images: {
  3. remotePatterns: [
  4. {
  5. protocol: 'https',
  6. hostname: '*.nextjswp.**' // <-- Change this to your WordPress site
  7. }
  8. ]
  9. }
  10. }

5. Configure /lib/config.ts

Open /lib/config.ts and update the content to match your WordPress site:

  1. const config = {
  2. siteName: 'Next.js WordPress',
  3. siteDescription: "It's headless WordPress!",
  4. siteUrl: 'https://nextjswp.com',
  5. revalidation: 3600
  6. }

6. Configure WordPress

Plugins

You’ll need either a local or public WordPress site with the following plugins:

WP-Config

After installing all the plugins mentioned above, you’ll need to add some constants to your wp-config.php file:

  1. // The URL of your Next.js frontend. Include the trailing slash.
  2. define( 'NEXTJS_FRONTEND_URL', 'https://nextjswp.com/' );
  3. // Optional. JWT auth refresh token.
  4. //define( 'GRAPHQL_JWT_AUTH_SECRET_KEY', '' );
  5. // Any random string. This must match the .env variable in the Next.js frontend.
  6. define( 'NEXTJS_PREVIEW_SECRET', 'preview' );
  7. // Any random string. This must match the .env variable in the Next.js frontend.
  8. define( 'NEXTJS_REVALIDATION_SECRET', 'revalidate' );

Finally, set your permalink structure to /blog/%postname%/ in Settings -> Permalinks.

7. Optional. Authentication for Previews

In order to query draft posts for Previews, you’ll need to authenticate with WordPress. The following is a one-time step:

  1. // Optional. JWT auth refresh token.
  2. define( 'GRAPHQL_JWT_AUTH_SECRET_KEY', 'the-random-string-generated-by-wp-salt' );
  • Go to GraphQL -> GraphiQL IDE in your WordPress admin
  • Copy the following and paste into GraphiQL IDE (replace your_username and your_password with your WordPress credentials)
  1. mutation Login {
  2. login(
  3. input: {
  4. clientMutationId: "uniqueId"
  5. password: "your_password"
  6. username: "your_username"
  7. }
  8. ) {
  9. refreshToken
  10. }
  11. }
  • Click the Play button in GraphiQL to run the mutation
  • Copy the refreshToken returned by the mutation
  • Open the Next.js .env.local file, and paste the refreshToken into the NEXTJS_AUTH_REFRESH_TOKEN variable
  1. # Optional. JWT auth refresh token.
  2. NEXTJS_AUTH_REFRESH_TOKEN="refresh-token-generated-by-grapqh-query"

You should now be able to preview draft posts in your Next.js app by clicking the Preview button in your WordPress admin.

8. Start the dev server

  1. npm run dev

Once the dev server has started, you can view the front-end: http://localhost:3000


Querying WordPress data with GraphQL

GraphQL is efficient because we can query multiple endpoints in a single request. If we were to use the WordPress REST-API, we would need to make multiple round trips to each respective endpoint.

We can build our queries in GraphiQL (or your favorite REST client) and let JSON.stringify() format it. Because this is all standard JavaScript, we can even pass variables to our queries— no need for a 3rd party package!

Here is a query to fetch a single post (based on the slug), the featured image, author meta, categories, tags, SEO, and post comments:

  1. import {Post} from '@/lib/types'
  2. /**
  3. * Fetch a single post by slug.
  4. */
  5. export async function getPostBySlug(slug: string) {
  6. // Define our query.
  7. const query = `
  8. query GetPost($slug: ID!) {
  9. post(id: $slug, idType: SLUG) {
  10. databaseId
  11. content(format: RENDERED)
  12. title(format: RENDERED)
  13. featuredImage {
  14. node {
  15. altText
  16. mediaDetails {
  17. sizes(include: MEDIUM) {
  18. height
  19. width
  20. sourceUrl
  21. }
  22. }
  23. }
  24. }
  25. author {
  26. node {
  27. avatar {
  28. url
  29. }
  30. name
  31. }
  32. }
  33. date
  34. tags {
  35. nodes {
  36. databaseId
  37. name
  38. }
  39. }
  40. categories {
  41. nodes {
  42. databaseId
  43. name
  44. }
  45. }
  46. seo {
  47. metaDesc
  48. title
  49. }
  50. comments(first: 30, where: {order: ASC}) {
  51. nodes {
  52. content(format: RENDERED)
  53. databaseId
  54. date
  55. status
  56. author {
  57. node {
  58. avatar {
  59. url
  60. }
  61. email
  62. name
  63. url
  64. }
  65. }
  66. }
  67. }
  68. }
  69. }
  70. `
  71. // Define our variables.
  72. const variables = {
  73. slug: slug
  74. }
  75. // Fetch the data using a reusable fetch function. Next.js
  76. // automatically memoizes and caches these requests.
  77. const response = await fetchGraphQL(query, variables)
  78. // Return the post.
  79. return response.data.post as Post
  80. }

This repo does not use a 3rd party GraphQL package, because Next.js automatically memoizes the fetch() requests in our custom fetch function. This means that if we fetch the same data twice, Next.js will only make one request to WordPress.

If you prefer use a 3rd party GraphQL package, simply swap out the custom fetchGraphQL() function with the package of your choosing.


Going To Production

Remember to add all the environment variables from .env.local to your production environment on Vercel or Netlify.


Other

RSS Feed, Sitemap, Robots.txt

Previews


Contributing

This is a hobby project and my time is limited, so your contributions are welcome! Please see the contributing guidelines to get started.