Unverified Commit 1207df68 authored by Bjørn Nyborg's avatar Bjørn Nyborg Committed by GitHub

examples: Updating WordPress example to Next 14 (#62447)

Updating the WordPress example, to a more modern example.

**Key features:**
- `robots.ts`: This automatically gets the robots.txt of the API route
and serves it on the `/robots.txt` route.
- `sitemap.ts`: This automatically gets all paths from the API and
generates a sitemap to serve on the `/sitemap.xml` route.
- `middleware.ts`: This contains a middleware function that checks the
users path for stored redirects, and redirects the user if a match is
found.
- `[[...slug]]`: This is the catch-all route that is used to render all
pages. It is important that this route is not removed, as it is used to
render all pages. It fetches the ContentType and renders the
corresponding
- `not-found.tsx`: This page is used for dynamic 404 handling - adjust
the database id to match your decired WordPress page, and make sure the
WordPress slug is "not-found", your 404 page will then be editable from
your CMS.
- `codegen.ts`: Automatic type generation for your WordPress
installation
- `Draft Mode`: Seamless Preview / Draft Preview support, using
authentication through WPGraphQL JWT Authentication and Next.js Draft
Mode
- `On Demand Cache Revalidation`: Including a bare minimum WordPress
theme that implements cache revalidation, WordPress link rewrites and
other utils for integrating with Next.js

✅ The "examples guidelines" are followed from our contributing doc
https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md

✅ Make sure the linting passes by running pnpm build && pnpm lint. See
https://github.com/vercel/next.js/blob/canary/contributing/repository/linting.md

---------
Co-authored-by: 's avatarSam Ko <sam@vercel.com>
parent 9f93a0cc
WORDPRESS_API_URL=
# Only required if you want to enable preview mode
# WORDPRESS_AUTH_REFRESH_TOKEN=
# WORDPRESS_PREVIEW_SECRET=
\ No newline at end of file
NEXT_PUBLIC_BASE_URL=
NEXT_PUBLIC_WORDPRESS_API_URL=
NEXT_PUBLIC_WORDPRESS_API_HOSTNAME=
HEADLESS_SECRET=
WP_USER=
WP_APP_PASS="
......@@ -27,6 +27,7 @@ yarn-error.log*
# local env files
.env*.local
.env
# vercel
.vercel
......@@ -34,3 +35,8 @@ yarn-error.log*
# typescript
*.tsbuildinfo
next-env.d.ts
certificates
#generated
gql
# An Incremental Static Regeneration Blog Example Using Next.js and WordPress
# A Feature Rich App Router WordPress Example
This example showcases Next.js's [Incremental Static Regeneration](https://nextjs.org/docs/basic-features/data-fetching/incremental-static-regeneration) feature using [WordPress](https://wordpress.org) as the data source.
This is an example on how you can build a Next.js 14 project (with App Router), using [WordPress](https://wordpress.org) as the data source.
## Demo
## Key features:
### [https://next-blog-wordpress.vercel.app](https://next-blog-wordpress.vercel.app)
- `robots.ts`: This automatically gets the robots.txt of the API route and serves it on the `/robots.txt` route.
- `sitemap.ts`: This automatically gets all paths from the API and generates a sitemap to serve on the `/sitemap.xml` route.
- `middleware.ts`: This contains a middleware function that checks the users path for stored redirects, and redirects the user if a match is found.
- `[[...slug]]`: This is the catch-all route that is used to render all pages. It is important that this route is not removed, as it is used to render all pages. It fetches the ContentType and renders the corresponding
- `not-found.tsx`: This page is used for dynamic 404 handling - adjust the database id to match your decired WordPress page, and make sure the WordPress slug is "not-found", your 404 page will then be editable from your CMS.
- `codegen.ts`: Automatic type generation for your WordPress installation
- `Draft Mode`: Seamless Preview / Draft Preview support, using authentication through WPGraphQL JWT Authentication and Next.js Draft Mode
- `On Demand Cache Revalidation`: Including a bare minimum WordPress theme that implements cache revalidation, WordPress link rewrites and other utils for integrating with Next.js
## Deploy your own
Once you have access to [the environment variables you'll need](#step-3-set-up-environment-variables), deploy the example using [Vercel](https://vercel.com?utm_source=github&utm_medium=readme&utm_campaign=next-example):
[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https://github.com/vercel/next.js/tree/canary/examples/cms-wordpress&project-name=cms-wordpress&repository-name=cms-wordpress&env=WORDPRESS_API_URL&envDescription=Required%20to%20connect%20the%20app%20with%20WordPress&envLink=https://vercel.link/cms-wordpress-env)
### Related examples
- [AgilityCMS](/examples/cms-agilitycms)
- [Builder.io](/examples/cms-builder-io)
- [ButterCMS](/examples/cms-buttercms)
- [Contentful](/examples/cms-contentful)
- [Cosmic](/examples/cms-cosmic)
- [DatoCMS](/examples/cms-datocms)
- [DotCMS](/examples/cms-dotcms)
- [Drupal](/examples/cms-drupal)
- [Enterspeed](/examples/cms-enterspeed)
- [Ghost](/examples/cms-ghost)
- [GraphCMS](/examples/cms-graphcms)
- [Kontent](/examples/cms-kontent-ai)
- [Prepr](/examples/cms-prepr)
- [Prismic](/examples/cms-prismic)
- [Sanity](/examples/cms-sanity)
- [Sitefinity](/examples/cms-sitefinity)
- [Storyblok](/examples/cms-storyblok)
- [TakeShape](/examples/cms-takeshape)
- [Umbraco heartcore](/examples/cms-umbraco-heartcore)
- [Webiny](/examples/cms-webiny)
- [Blog Starter](/examples/blog-starter)
- [WordPress](/examples/cms-wordpress)
Deploy the example using [Vercel](https://vercel.com?utm_source=github&utm_medium=readme&utm_campaign=next-example):
[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https://github.com/vercel/next.js/tree/canary/examples/cms-wordpress&project-name=cms-wordpress&repository-name=cms-wordpress)
## How to use
Execute [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app) with [npm](https://docs.npmjs.com/cli/init), [Yarn](https://yarnpkg.com/lang/en/docs/cli/create/), or [pnpm](https://pnpm.io) to bootstrap the example:
Execute [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app) with [npm](https://docs.npmjs.com/cli/init), [Yarn](https://yarnpkg.com/lang/en/docs/cli/create/), [pnpm](https://pnpm.io), or [Bun](https://bun.sh/docs/cli/bunx) to bootstrap the example:
```bash
npx create-next-app --example cms-wordpress cms-wordpress-app
......@@ -53,167 +35,395 @@ yarn create next-app --example cms-wordpress cms-wordpress-app
pnpm create next-app --example cms-wordpress cms-wordpress-app
```
## Configuration
### Step 1. Prepare your WordPress site
First, you need a WordPress site. There are many solutions for WordPress hosting, such as [WP Engine](https://wpengine.com/) and [WordPress.com](https://wordpress.com/).
Once the site is ready, you'll need to install the [WPGraphQL](https://www.wpgraphql.com/) plugin. It will add GraphQL API to your WordPress site, which we'll use to query the posts. Follow these steps to install it:
- Download the [WPGraphQL repo](https://github.com/wp-graphql/wp-graphql) as a ZIP archive.
- Inside your WordPress admin, go to **Plugins** and then click **Add New**.
![Add new plugin](./docs/plugins-add-new.png)
- Click the **Upload Plugin** button at the top of the page and upload the WPGraphQL plugin.
![Upload new plugin](./docs/plugins-upload-new.png)
- Once the plugin has been added, activate it from either the **Activate Plugin** button displayed after uploading or from the **Plugins** page.
![WPGraphQL installed](./docs/plugin-installed.png)
#### GraphiQL
The [WPGraphQL](https://www.wpgraphql.com/) plugin also gives you access to a GraphQL IDE directly from your WordPress Admin, allowing you to inspect and play around with the GraphQL API.
```bash
bunx create-next-app --example cms-wordpress cms-wordpress-app
```
![WPGraphiQL page](./docs/wp-graphiql.png)
Deploy it to the cloud with [Vercel](https://vercel.com/new?utm_source=github&utm_medium=readme&utm_campaign=next-example) ([Documentation](https://nextjs.org/docs/deployment)).
### Step 2. Populate Content
## Configuration
Inside your WordPress admin, go to **Posts** and start adding new posts:
### WordPress
1. Set `Site Address (URL)` to your frontend URL, e.g. `https://localhost:3000` in Settings -> General
2. Make sure Permalinks are set to `Post name` in Settings -> Permalinks
3. Set `Sample page` as `Static page` in Settings -> Reading
4. Create a new page called `404 not found` ensuring the slug is `404-not-found`
5. Install and activate following plugins:
- Add WPGraphQL SEO
- Classic Editor
- Redirection
- WPGraphQL
- [WPGraphQL JWT Authentication](https://github.com/wp-graphql/wp-graphql-jwt-authentication/releases)
- Yoast SEO
- [Advanced Custom Fields PRO](https://www.advancedcustomfields.com/pro/) (optional)
- WPGraphQL for ACF (optional)
6. Do first-time install of Redirection. Recommended to enable monitor of changes
7. Configure Yoast SEO with:
- Disable XML Sitemaps under Yoast SEO -> Settings
- If you did not change the `Site Address (URL)` before installing Yoast, it will ask you to run optimize SEO data after changing permalinks, do so
- Generate a robots.txt file under Yoast SEO -> Tools -> File Editor
- Modify robots.txt sitemap reference from `wp-sitemap.xml` to `sitemap.xml`
8. `Enable Public Introspection` under GraphQL -> Settings
9. Add following constants to `wp-config.php`
```php
define('HEADLESS_SECRET', 'INSERT_RANDOM_SECRET_KEY');
define('HEADLESS_URL', 'INSERT_LOCAL_DEVELOPMENT_URL'); // http://localhost:3000 for local development
define('GRAPHQL_JWT_AUTH_SECRET_KEY', 'INSERT_RANDOM_SECRET_KEY');
define('GRAPHQL_JWT_AUTH_CORS_ENABLE', true);
```
10. Create a bare minimum custom WordPress theme, consisting of only 2 files:
- [style.css](https://developer.wordpress.org/themes/basics/main-stylesheet-style-css/#basic-structure)
- functions.php (see the bottom of this README)
### Next.js
1. Clone the repository
2. Run `npm install` to install dependencies
3. Create `.env` file in the root directory and add the following variables:
| Name | Value | Example | Description |
| ------------------------------------ | ----------------------------------------------------------------------- | ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `NEXT_PUBLIC_BASE_URL` | Insert base url of frontend | http://localhost:3000 | Used for generating sitemap, redirects etc. |
| `NEXT_PUBLIC_WORDPRESS_API_URL` | Insert base url of your WordPress installation | http://wp-domain.com | Used when requesting wordpress for data |
| `NEXT_PUBLIC_WORDPRESS_API_HOSTNAME` | The hostname without protocol for your WordPress installation | wp-domain.com | Used for dynamically populating the next.config images remotePatterns |
| `HEADLESS_SECRET` | Insert the same random key, that you generated for your `wp-config.php` | INSERT_RANDOM_SECRET_KEY | Used for public exhanges between frontend and backend |
| `WP_USER` | Insert a valid WordPress username | username | Username for a system user created specifically for interacting with your WordPress installation |
| `WP_APP_PASS` | Insert application password | 1234 5678 abcd efgh | [Generate an application password](https://make.wordpress.org/core/2020/11/05/application-passwords-integration-guide/) for the WordPress user defined in `WP_USER` |
> [!WARNING] > `WP_USER` and `WP_APP_PASS` are critical for making preview and redirection work
4. Adjust the ID in `not-found.tsx` to match the post id of your "404 Not Found" page in WordPress
5. `npm run dev` and build an awesome application with WordPress!
> [!NOTE] > Running `npm run dev` will automatically generate typings from the WordPress installation found on the url provided in your environment variable: `NEXT_PUBLIC_WORDPRESS_API_URL`
## GraphQL and typescript types
We are generating typescript types from the provided schema with Codegen.
### Enabling Auto Completion for graphql queries
If you want to add auto completion for your queries, you can do this by installing the "Apollo GraphQL" extension in VS Code and adding an `apollo.config.js` file, next to the `next.config.js`, and add the following to it:
```javascript
module.exports = {
client: {
service: {
name: "WordPress",
localSchemaFile: "./src/gql/schema.gql",
},
},
};
```
- We recommend creating at least **2 posts**
- Use dummy data for the content
- Pick an author from your WordPress users
- Add a **Featured Image**. You can download one from [Unsplash](https://unsplash.com/)
- Fill the **Excerpt** field
## Advanced Custom Fields PRO (optional, but recommended)
![New post](./docs/new-post.png)
I will recommend building your page content by using the [Flexible Content](https://www.advancedcustomfields.com/resources/flexible-content/) data type in ACF Pro.
This will make you able to create a "Block Builder" editor experience, but still having everything automatically type generated, and recieving the data in a structured way.
The default "Gutenberg" editor returns a lot of HTML, which makes you loose a lot of the advantages of using GraphQL with type generation.
When you’re done, make sure to **Publish** the posts.
## Redirection setup
> **Note:** Only **published** posts and public fields will be rendered by the app unless [Preview Mode](https://nextjs.org/docs/advanced-features/preview-mode) is enabled.
The example supports the WordPress "Redirection" plugin. the `WP_USER` and `WP_APP_PASS` environment variables are required, for this to work. By implementing this you can manage redirects for your content, through your WordPress CMS
### Step 3. Set up environment variables
## Draft / Preview support
Copy the `.env.local.example` file in this directory to `.env.local` (which will be ignored by Git):
The example supports WordPress preview (also draft preview), when enabling `draftMode` in the `api/preview/route.ts` it logs the `WP_USER` in with the `WP_APP_PASS` and requests the GraphQL as an authenticated user. This makes draft and preview available. If a post is in "draft" status, it doesn't have a real slug. In this case we redirect to a "fake" route called `/preview/${id}` and uses the supplied id for fetching data for the post.
```bash
cp .env.local.example .env.local
```
## Cache Revalidation
Then open `.env.local` and set `WORDPRESS_API_URL` to be the URL to your GraphQL endpoint in WordPress. For example: `https://myapp.wpengine.com/graphql`.
All our GraphQL requests has the cache tag `wordpress` - when we update anything in WordPress, we call our `/api/revalidate` route, and revalidates the `wordpress` tag. In this way we ensure that everything is up to date, but only revalidate the cache when there actually are updates.
Your `.env.local` file should look like this:
## Template handling
```bash
WORDPRESS_API_URL=...
We use an "Optional Catch-all Segment" for handling all WordPress content.
When rendering this component we simply ask GraphQL "what type of content is this route?" and fetch the corresponding template.
Each template can then have their own queries for fetching specific content for that template.
# Only required if you want to enable preview mode
# WORDPRESS_AUTH_REFRESH_TOKEN=
# WORDPRESS_PREVIEW_SECRET=
```
## SEO
### Step 4. Run Next.js in development mode
We are using Yoast SEO for handling SEO in WordPress, and then all routes are requesting the Yoast SEO object, and parsing this to a dynamic `generateMetadata()` function
```bash
npm install
npm run dev
## Folder structure
# or
The boilerplate is structured as follows:
yarn install
yarn dev
```
- `app`: Contains the routes and pages of the application
- `assets`: Contains helpful styles such as the variables
- `components`: Contains the components used in the application
- `gql`: Contains auto-generated types from GraphQL via CodeGen
- `queries`: Contains reusable data fetch requests to GraphQL
- `utils`: Contains helpful functions used across the application
Your blog should be up and running on [http://localhost:3000](http://localhost:3000)! If it doesn't work, post on [GitHub discussions](https://github.com/vercel/next.js/discussions).
## WordPress theme functions.php
### Step 5. Add authentication for Preview Mode (Optional)
This `functions.php` is implementing different useful features for using WordPress with Next.js:
**This step is optional.** By default, the blog will work with public posts from your WordPress site. Private content such as unpublished posts and private fields cannot be retrieved. To have access to unpublished posts you'll need to set up authentication.
- Setting up a primary menu (fetched in `Navigation..tsx`)
- Rewriting preview and rest links to match the frontend instead of the WordPress installation
- Implementing cache tag revalidation everytime you update a post in WordPress
- Implementing rest endpoints for sitemap generation
To add [authentication to WPGraphQL](https://docs.wpgraphql.com/guides/authentication-and-authorization/), first you need to add the [WPGraphQL JWT plugin](https://github.com/wp-graphql/wp-graphql-jwt-authentication) to your WordPress Admin following the same process you used to add the WPGraphQL plugin.
```php
<?php
/**
* Registers new menus
*
* @return void
*/
add_action('init', 'register_new_menu');
function register_new_menu()
{
register_nav_menus(
array(
'primary-menu' => __('Primary menu')
)
);
}
> Adding the WPGraphQL JWT plugin will disable your GraphQL API until you add a JWT secret ([GitHub issue](https://github.com/wp-graphql/wp-graphql-jwt-authentication/issues/91)).
/**
* Changes the REST API root URL to use the home URL as the base.
*
* @param string $url The complete URL including scheme and path.
* @return string The REST API root URL.
*/
add_filter('rest_url', 'home_url_as_api_url');
function home_url_as_api_url($url)
{
$url = str_replace(home_url(), site_url(), $url);
return $url;
}
Once that's done, you'll need to access the WordPress filesystem to add the secret required to validate JWT tokens. We recommend using SFTP — the instructions vary depending on your hosting provider. For example:
/**
* Customize the preview button in the WordPress admin.
*
* This function modifies the preview link for a post to point to a headless client setup.
*
* @param string $link Original WordPress preview link.
* @param WP_Post $post Current post object.
* @return string Modified headless preview link.
*/
add_filter( 'preview_post_link', 'set_headless_preview_link', 10, 2 );
function set_headless_preview_link( string $link, WP_Post $post ): string {
// Set the front-end preview route.
$frontendUrl = HEADLESS_URL;
// Update the preview link in WordPress.
return add_query_arg(
[
'secret' => HEADLESS_SECRET,
'id' => $post->ID,
],
esc_url_raw( esc_url_raw( "$frontendUrl/api/preview" ))
);
}
- [SFTP guide for WP Engine](https://wpengine.com/support/sftp/)
- [SFTP guide for WordPress.com](https://wordpress.com/support/sftp/)
add_filter( 'rest_prepare_page', 'set_headless_rest_preview_link', 10, 2 );
add_filter( 'rest_prepare_post', 'set_headless_rest_preview_link' , 10, 2 );
function set_headless_rest_preview_link( WP_REST_Response $response, WP_Post $post ): WP_REST_Response {
// Check if the post status is 'draft' and set the preview link accordingly.
if ( 'draft' === $post->post_status ) {
$response->data['link'] = get_preview_post_link( $post );
return $response;
}
Once you have SFTP access, open `wp-config.php` and add a secret for your JWT:
// For published posts, modify the permalink to point to the frontend.
if ( 'publish' === $post->post_status ) {
```php
define( 'GRAPHQL_JWT_AUTH_SECRET_KEY', 'YOUR_STRONG_SECRET' );
```
// Get the post permalink.
$permalink = get_permalink( $post );
> You can read more about this in the documentation for [WPGraphQL JWT Authentication](https://docs.wpgraphql.com/extensions/wpgraphql-jwt-authentication/).
// Check if the permalink contains the site URL.
if ( false !== stristr( $permalink, get_site_url() ) ) {
Now, you need to get a **refresh token** to make authenticated requests with GraphQL. Make the following GraphQL mutation to your WordPress site from the GraphQL IDE (See notes about WPGraphiQL from earlier). Replace `your_username` with the **username** of a user with the `Administrator` role, and `your_password` with the user's password.
$frontendUrl = HEADLESS_URL;
```graphql
mutation Login {
login(
input: {
clientMutationId: "uniqueId"
password: "your_password"
username: "your_username"
// Replace the site URL with the frontend URL.
$response->data['link'] = str_ireplace(
get_site_url(),
$frontendUrl,
$permalink
);
}
) {
refreshToken
}
return $response;
}
```
Copy the `refreshToken` returned by the mutation, then open `.env.local`, and make the following changes:
- Uncomment `WORDPRESS_AUTH_REFRESH_TOKEN` and set it to be the `refreshToken` you just received.
- Uncomment `WORDPRESS_PREVIEW_SECRET` and set it to be any random string (ideally URL friendly).
/**
* Adds the headless_revalidate function to the save_post action hook.
* This function makes a PUT request to the headless site' api/revalidate endpoint with JSON body: paths = ['/path/to/page', '/path/to/another/page']
* Requires HEADLESS_URL and HEADLESS_SECRET to be defined in wp-config.php
*
* @param int $post_ID The ID of the post being saved.
* @return void
*/
add_action('transition_post_status', 'headless_revalidate', 10, 3);
function headless_revalidate(string $new_status, string $old_status, object $post ): void
{
if ( ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) || ( defined( 'DOING_CRON' ) && DOING_CRON ) ) {
return;
}
Your `.env.local` file should look like this:
// Ignore drafts and inherited posts.
if ( ( 'draft' === $new_status && 'draft' === $old_status ) || 'inherit' === $new_status ) {
return;
}
```bash
WORDPRESS_API_URL=...
$frontendUrl = HEADLESS_URL;
$headlessSecret = HEADLESS_SECRET;
$data = json_encode([
'tags' => ['wordpress'],
]);
$response = wp_remote_request("$frontendUrl/api/revalidate/", [
'method' => 'PUT',
'body' => $data,
'headers' => [
'X-Headless-Secret-Key' => $headlessSecret,
'Content-Type' => 'application/json',
],
]);
// Check if the request was successful
if (is_wp_error($response)) {
// Handle error
error_log($response->get_error_message());
}
}
# Only required if you want to enable preview mode
WORDPRESS_AUTH_REFRESH_TOKEN=...
WORDPRESS_PREVIEW_SECRET=...
```
function wsra_get_user_inputs()
{
$pageNo = sprintf("%d", $_GET['pageNo']);
$perPage = sprintf("%d", $_GET['perPage']);
// Check for array key taxonomyType
if (array_key_exists('taxonomyType', $_GET)) {
$taxonomy = $_GET['taxonomyType'];
} else {
$taxonomy = 'category';
}
$postType = $_GET['postType'];
$paged = $pageNo ? $pageNo : 1;
$perPage = $perPage ? $perPage : 100;
$offset = ($paged - 1) * $perPage;
$args = array(
'number' => $perPage,
'offset' => $offset,
);
$postArgs = array(
'posts_per_page' => $perPage,
'post_type' => strval($postType ? $postType : 'post'),
'paged' => $paged,
);
return [$args, $postArgs, $taxonomy];
}
**Important:** Restart your Next.js server to update the environment variables.
function wsra_generate_author_api()
{
[$args] = wsra_get_user_inputs();
$author_urls = array();
$authors = get_users($args);
foreach ($authors as $author) {
$fullUrl = esc_url(get_author_posts_url($author->ID));
$url = str_replace(home_url(), '', $fullUrl);
$tempArray = [
'url' => $url,
];
array_push($author_urls, $tempArray);
}
return array_merge($author_urls);
}
### Step 6. Try preview mode
function wsra_generate_taxonomy_api()
{
[$args,, $taxonomy] = wsra_get_user_inputs();
$taxonomy_urls = array();
$taxonomys = $taxonomy == 'tag' ? get_tags($args) : get_categories($args);
foreach ($taxonomys as $taxonomy) {
$fullUrl = esc_url(get_category_link($taxonomy->term_id));
$url = str_replace(home_url(), '', $fullUrl);
$tempArray = [
'url' => $url,
];
array_push($taxonomy_urls, $tempArray);
}
return array_merge($taxonomy_urls);
}
On your WordPress admin, create a new post like before, but **do not publish** it.
function wsra_generate_posts_api()
{
[, $postArgs] = wsra_get_user_inputs();
$postUrls = array();
$query = new WP_Query($postArgs);
while ($query->have_posts()) {
$query->the_post();
$uri = str_replace(home_url(), '', get_permalink());
$tempArray = [
'url' => $uri,
'post_modified_date' => get_the_modified_date(),
];
array_push($postUrls, $tempArray);
}
wp_reset_postdata();
return array_merge($postUrls);
}
Now, if you go to `http://localhost:3000`, you won’t see the post. However, if you enable **Preview Mode**, you'll be able to see the change ([Documentation](https://nextjs.org/docs/advanced-features/preview-mode)).
function wsra_generate_totalpages_api()
{
$args = array(
'exclude_from_search' => false
);
$argsTwo = array(
'publicly_queryable' => true
);
$post_types = get_post_types($args, 'names');
$post_typesTwo = get_post_types($argsTwo, 'names');
$post_types = array_merge($post_types, $post_typesTwo);
unset($post_types['attachment']);
$defaultArray = [
'category' => count(get_categories()),
'tag' => count(get_tags()),
'user' => (int)count_users()['total_users'],
];
$tempValueHolder = array();
foreach ($post_types as $postType) {
$tempValueHolder[$postType] = (int)wp_count_posts($postType)->publish;
}
return array_merge($defaultArray, $tempValueHolder);
}
To enable Preview Mode, go to this URL:
add_action('rest_api_init', function () {
register_rest_route('sitemap/v1', '/posts', array(
'methods' => 'GET',
'callback' => 'wsra_generate_posts_api',
));
});
add_action('rest_api_init', function () {
register_rest_route('sitemap/v1', '/taxonomy', array(
'methods' => 'GET',
'callback' => 'wsra_generate_taxonomy_api',
));
});
add_action('rest_api_init', function () {
register_rest_route('sitemap/v1', '/author', array(
'methods' => 'GET',
'callback' => 'wsra_generate_author_api',
));
});
add_action('rest_api_init', function () {
register_rest_route('sitemap/v1', '/totalpages', array(
'methods' => 'GET',
'callback' => 'wsra_generate_totalpages_api',
));
});
```
http://localhost:3000/api/preview?secret=<secret>&id=<id>
```
- `<secret>` should be the string you entered for `WORDPRESS_PREVIEW_SECRET`.
- `<id>` should be the post's `databaseId` field, which is the integer that you usually see in the URL (`?post=18` → 18).
- Alternatively, you can use `<slug>` instead of `<id>`. `<slug>` is generated based on the title.
You should now be able to see this post. To exit Preview Mode, you can click on **Click here to exit preview mode** at the top.
### Step 7. Deploy on Vercel
You can deploy this app to the cloud with [Vercel](https://vercel.com?utm_source=github&utm_medium=readme&utm_campaign=next-example) ([Documentation](https://nextjs.org/docs/deployment)).
#### Deploy Your Local Project
To deploy your local project to Vercel, push it to GitHub/GitLab/Bitbucket and [import to Vercel](https://vercel.com/new?utm_source=github&utm_medium=readme&utm_campaign=next-example).
**Important**: When you import your project on Vercel, make sure to click on **Environment Variables** and set them to match your `.env.local` file.
#### Deploy from Our Template
Alternatively, you can deploy using our template by clicking on the Deploy button below.
[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https://github.com/vercel/next.js/tree/canary/examples/cms-wordpress&project-name=cms-wordpress&repository-name=cms-wordpress&env=WORDPRESS_API_URL&envDescription=Required%20to%20connect%20the%20app%20with%20WordPress&envLink=https://vercel.link/cms-wordpress-env)
const fs = require("fs");
const generatedFilePath = "src/gql/gql.ts";
fs.readFile(generatedFilePath, "utf8", (err, data) => {
if (err) {
console.error("Error reading file:", err);
return;
}
const updatedContent = `// @ts-nocheck\n${data}`;
fs.writeFile(generatedFilePath, updatedContent, "utf8", (err) => {
if (err) {
console.error("Error writing file:", err);
} else {
console.log(`Added "// @ts-nocheck" to ${generatedFilePath}`);
}
});
});
import type { CodegenConfig } from "@graphql-codegen/cli";
import { loadEnvConfig } from "@next/env";
const projectDir = process.cwd();
loadEnvConfig(projectDir);
const config: CodegenConfig = {
overwrite: true,
schema: {
[`${process.env.NEXT_PUBLIC_WORDPRESS_API_URL}/graphql`]: {
headers: {
"User-Agent": "Codegen",
},
},
},
generates: {
"src/gql/": {
preset: "client",
},
"src/gql/schema.gql": {
plugins: ["schema-ast"],
},
},
};
export default config;
import Container from "./container";
import cn from "classnames";
import { EXAMPLE_PATH } from "../lib/constants";
export default function Alert({ preview }) {
return (
<div
className={cn("border-b", {
"bg-accent-7 border-accent-7 text-white": preview,
"bg-accent-1 border-accent-2": !preview,
})}
>
<Container>
<div className="py-2 text-center text-sm">
{preview ? (
<>
This is a page preview.{" "}
<a
href="/api/exit-preview"
className="underline hover:text-cyan duration-200 transition-colors"
>
Click here
</a>{" "}
to exit preview mode.
</>
) : (
<>
The source code for this blog is{" "}
<a
href={`https://github.com/vercel/next.js/tree/canary/examples/${EXAMPLE_PATH}`}
className="underline hover:text-success duration-200 transition-colors"
>
available on GitHub
</a>
.
</>
)}
</div>
</Container>
</div>
);
}
import Image from "next/image";
export default function Avatar({ author }) {
const isAuthorHaveFullName =
author?.node?.firstName && author?.node?.lastName;
const name = isAuthorHaveFullName
? `${author.node.firstName} ${author.node.lastName}`
: author.node.name || null;
return (
<div className="flex items-center">
<div className="w-12 h-12 relative mr-4">
<Image
src={author.node.avatar.url}
layout="fill"
className="rounded-full"
alt={name}
/>
</div>
<div className="text-xl font-bold">{name}</div>
</div>
);
}
export default function Categories({ categories }) {
return (
<span className="ml-1">
under
{categories.edges.length > 0 ? (
categories.edges.map((category, index) => (
<span key={index} className="ml-1">
{category.node.name}
</span>
))
) : (
<span className="ml-1">{categories.edges.node.name}</span>
)}
</span>
);
}
export default function Container({ children }) {
return <div className="container mx-auto px-5">{children}</div>;
}
import cn from "classnames";
import Image from "next/image";
import Link from "next/link";
interface Props {
title: string;
coverImage: {
node: {
sourceUrl: string;
};
};
slug?: string;
}
export default function CoverImage({ title, coverImage, slug }: Props) {
const image = (
<Image
width={2000}
height={1000}
alt={`Cover Image for ${title}`}
src={coverImage?.node.sourceUrl}
className={cn("shadow-small", {
"hover:shadow-medium transition-shadow duration-200": slug,
})}
/>
);
return (
<div className="sm:mx-0">
{slug ? (
<Link href={`/posts/${slug}`} aria-label={title}>
{image}
</Link>
) : (
image
)}
</div>
);
}
import { parseISO, format } from "date-fns";
export default function Date({ dateString }) {
const date = parseISO(dateString);
return <time dateTime={dateString}>{format(date, "LLLL d, yyyy")}</time>;
}
import Container from "./container";
import { EXAMPLE_PATH } from "../lib/constants";
export default function Footer() {
return (
<footer className="bg-accent-1 border-t border-accent-2">
<Container>
<div className="py-28 flex flex-col lg:flex-row items-center">
<h3 className="text-4xl lg:text-5xl font-bold tracking-tighter leading-tight text-center lg:text-left mb-10 lg:mb-0 lg:pr-4 lg:w-1/2">
Statically Generated with Next.js.
</h3>
<div className="flex flex-col lg:flex-row justify-center items-center lg:pl-4 lg:w-1/2">
<a
href="https://nextjs.org/docs/basic-features/pages"
className="mx-3 bg-black hover:bg-white hover:text-black border border-black text-white font-bold py-3 px-12 lg:px-8 duration-200 transition-colors mb-6 lg:mb-0"
>
Read Documentation
</a>
<a
href={`https://github.com/vercel/next.js/tree/canary/examples/${EXAMPLE_PATH}`}
className="mx-3 font-bold hover:underline"
>
View on GitHub
</a>
</div>
</div>
</Container>
</footer>
);
}
import Link from "next/link";
export default function Header() {
return (
<h2 className="text-2xl md:text-4xl font-bold tracking-tight md:tracking-tighter leading-tight mb-20 mt-8">
<Link href="/" className="hover:underline">
Blog
</Link>
.
</h2>
);
}
import Avatar from "./avatar";
import Date from "./date";
import CoverImage from "./cover-image";
import Link from "next/link";
export default function HeroPost({
title,
coverImage,
date,
excerpt,
author,
slug,
}) {
return (
<section>
<div className="mb-8 md:mb-16">
{coverImage && (
<CoverImage title={title} coverImage={coverImage} slug={slug} />
)}
</div>
<div className="md:grid md:grid-cols-2 md:gap-x-16 lg:gap-x-8 mb-20 md:mb-28">
<div>
<h3 className="mb-4 text-4xl lg:text-6xl leading-tight">
<Link
href={`/posts/${slug}`}
className="hover:underline"
dangerouslySetInnerHTML={{ __html: title }}
></Link>
</h3>
<div className="mb-4 md:mb-0 text-lg">
<Date dateString={date} />
</div>
</div>
<div>
<div
className="text-lg leading-relaxed mb-4"
dangerouslySetInnerHTML={{ __html: excerpt }}
/>
<Avatar author={author} />
</div>
</div>
</section>
);
}
import { CMS_NAME, CMS_URL } from "../lib/constants";
export default function Intro() {
return (
<section className="flex-col md:flex-row flex items-center md:justify-between mt-16 mb-16 md:mb-12">
<h1 className="text-6xl md:text-8xl font-bold tracking-tighter leading-tight md:pr-8">
Blog.
</h1>
<h4 className="text-center md:text-left text-lg mt-5 md:pl-8">
A statically generated blog example using{" "}
<a
href="https://nextjs.org/"
className="underline hover:text-success duration-200 transition-colors"
>
Next.js
</a>{" "}
and{" "}
<a
href={CMS_URL}
className="underline hover:text-success duration-200 transition-colors"
>
{CMS_NAME}
</a>
.
</h4>
</section>
);
}
import Alert from "./alert";
import Footer from "./footer";
import Meta from "./meta";
export default function Layout({ preview, children }) {
return (
<>
<Meta />
<div className="min-h-screen">
<Alert preview={preview} />
<main>{children}</main>
</div>
<Footer />
</>
);
}
import Head from "next/head";
import { CMS_NAME, HOME_OG_IMAGE_URL } from "../lib/constants";
export default function Meta() {
return (
<Head>
<link
rel="apple-touch-icon"
sizes="180x180"
href="/favicon/apple-touch-icon.png"
/>
<link
rel="icon"
type="image/png"
sizes="32x32"
href="/favicon/favicon-32x32.png"
/>
<link
rel="icon"
type="image/png"
sizes="16x16"
href="/favicon/favicon-16x16.png"
/>
<link rel="manifest" href="/favicon/site.webmanifest" />
<link
rel="mask-icon"
href="/favicon/safari-pinned-tab.svg"
color="#000000"
/>
<link rel="shortcut icon" href="/favicon/favicon.ico" />
<meta name="msapplication-TileColor" content="#000000" />
<meta name="msapplication-config" content="/favicon/browserconfig.xml" />
<meta name="theme-color" content="#000" />
<link rel="alternate" type="application/rss+xml" href="/feed.xml" />
<meta
name="description"
content={`A statically generated blog example using Next.js and ${CMS_NAME}.`}
/>
<meta property="og:image" content={HOME_OG_IMAGE_URL} />
</Head>
);
}
import PostPreview from "./post-preview";
export default function MoreStories({ posts }) {
return (
<section>
<h2 className="mb-8 text-6xl md:text-7xl font-bold tracking-tighter leading-tight">
More Stories
</h2>
<div className="grid grid-cols-1 md:grid-cols-2 md:gap-x-16 lg:gap-x-32 gap-y-20 md:gap-y-32 mb-32">
{posts.map(({ node }) => (
<PostPreview
key={node.slug}
title={node.title}
coverImage={node.featuredImage}
date={node.date}
author={node.author}
slug={node.slug}
excerpt={node.excerpt}
/>
))}
</div>
</section>
);
}
.content {
@apply text-lg leading-relaxed;
}
.content p,
.content ul,
.content ol,
.content blockquote {
@apply my-6;
}
.content a {
@apply underline;
}
.content ul,
.content ol {
@apply pl-4;
}
.content ul {
@apply list-disc;
}
.content ol {
@apply list-decimal;
}
.content ul > li > ul,
.content ol > li > ol {
@apply my-0 ml-4;
}
.content ul > li > ul {
list-style: circle;
}
.content h2 {
@apply text-3xl mt-12 mb-4 leading-snug;
}
.content h3 {
@apply text-2xl mt-8 mb-4 leading-snug;
}
.content h4 {
@apply text-xl mt-6 mb-4 leading-snug;
}
.content pre {
@apply whitespace-pre overflow-x-auto p-4 text-sm leading-tight border border-gray-400 bg-gray-100;
}
.content code {
@apply text-sm;
}
.content figcaption {
@apply text-center text-sm;
}
.content blockquote {
@apply border-l-4 border-gray-500 bg-gray-200 italic ml-0 py-4 px-6;
}
.content blockquote p {
@apply mt-0;
}
.content blockquote cite {
@apply not-italic;
}
.content audio {
@apply w-full;
}
import styles from "./post-body.module.css";
export default function PostBody({ content }) {
return (
<div className="max-w-2xl mx-auto">
<div
className={styles.content}
dangerouslySetInnerHTML={{ __html: content }}
/>
</div>
);
}
import Avatar from "./avatar";
import Date from "./date";
import CoverImage from "./cover-image";
import PostTitle from "./post-title";
import Categories from "./categories";
export default function PostHeader({
title,
coverImage,
date,
author,
categories,
}) {
return (
<>
<PostTitle>{title}</PostTitle>
<div className="hidden md:block md:mb-12">
<Avatar author={author} />
</div>
<div className="mb-8 md:mb-16 sm:mx-0">
<CoverImage title={title} coverImage={coverImage} />
</div>
<div className="max-w-2xl mx-auto">
<div className="block md:hidden mb-6">
<Avatar author={author} />
</div>
<div className="mb-6 text-lg">
Posted <Date dateString={date} />
<Categories categories={categories} />
</div>
</div>
</>
);
}
import Avatar from "./avatar";
import Date from "./date";
import CoverImage from "./cover-image";
import Link from "next/link";
export default function PostPreview({
title,
coverImage,
date,
excerpt,
author,
slug,
}) {
return (
<div>
<div className="mb-5">
{coverImage && (
<CoverImage title={title} coverImage={coverImage} slug={slug} />
)}
</div>
<h3 className="text-3xl mb-3 leading-snug">
<Link
href={`/posts/${slug}`}
className="hover:underline"
dangerouslySetInnerHTML={{ __html: title }}
></Link>
</h3>
<div className="text-lg mb-4">
<Date dateString={date} />
</div>
<div
className="text-lg leading-relaxed mb-4"
dangerouslySetInnerHTML={{ __html: excerpt }}
/>
<Avatar author={author} />
</div>
);
}
export default function PostTitle({ children }) {
return (
<h1
className="text-6xl md:text-7xl lg:text-8xl font-bold tracking-tighter leading-tight md:leading-none mb-12 text-center md:text-left"
dangerouslySetInnerHTML={{ __html: children }}
/>
);
}
export default function SectionSeparator() {
return <hr className="border-accent-2 mt-28 mb-24" />;
}
export default function Tags({ tags }) {
return (
<div className="max-w-2xl mx-auto">
<p className="mt-8 text-lg font-bold">
Tagged
{tags.edges.map((tag, index) => (
<span key={index} className="ml-4 font-normal">
{tag.node.name}
</span>
))}
</p>
</div>
);
}
const API_URL = process.env.WORDPRESS_API_URL;
async function fetchAPI(query = "", { variables }: Record<string, any> = {}) {
const headers = { "Content-Type": "application/json" };
if (process.env.WORDPRESS_AUTH_REFRESH_TOKEN) {
headers["Authorization"] =
`Bearer ${process.env.WORDPRESS_AUTH_REFRESH_TOKEN}`;
}
// WPGraphQL Plugin must be enabled
const res = await fetch(API_URL, {
headers,
method: "POST",
body: JSON.stringify({
query,
variables,
}),
});
const json = await res.json();
if (json.errors) {
console.error(json.errors);
throw new Error("Failed to fetch API");
}
return json.data;
}
export async function getPreviewPost(id, idType = "DATABASE_ID") {
const data = await fetchAPI(
`
query PreviewPost($id: ID!, $idType: PostIdType!) {
post(id: $id, idType: $idType) {
databaseId
slug
status
}
}`,
{
variables: { id, idType },
},
);
return data.post;
}
export async function getAllPostsWithSlug() {
const data = await fetchAPI(`
{
posts(first: 10000) {
edges {
node {
slug
}
}
}
}
`);
return data?.posts;
}
export async function getAllPostsForHome(preview) {
const data = await fetchAPI(
`
query AllPosts {
posts(first: 20, where: { orderby: { field: DATE, order: DESC } }) {
edges {
node {
title
excerpt
slug
date
featuredImage {
node {
sourceUrl
}
}
author {
node {
name
firstName
lastName
avatar {
url
}
}
}
}
}
}
}
`,
{
variables: {
onlyEnabled: !preview,
preview,
},
},
);
return data?.posts;
}
export async function getPostAndMorePosts(slug, preview, previewData) {
const postPreview = preview && previewData?.post;
// The slug may be the id of an unpublished post
const isId = Number.isInteger(Number(slug));
const isSamePost = isId
? Number(slug) === postPreview.id
: slug === postPreview.slug;
const isDraft = isSamePost && postPreview?.status === "draft";
const isRevision = isSamePost && postPreview?.status === "publish";
const data = await fetchAPI(
`
fragment AuthorFields on User {
name
firstName
lastName
avatar {
url
}
}
fragment PostFields on Post {
title
excerpt
slug
date
featuredImage {
node {
sourceUrl
}
}
author {
node {
...AuthorFields
}
}
categories {
edges {
node {
name
}
}
}
tags {
edges {
node {
name
}
}
}
}
query PostBySlug($id: ID!, $idType: PostIdType!) {
post(id: $id, idType: $idType) {
...PostFields
content
${
// Only some of the fields of a revision are considered as there are some inconsistencies
isRevision
? `
revisions(first: 1, where: { orderby: { field: MODIFIED, order: DESC } }) {
edges {
node {
title
excerpt
content
author {
node {
...AuthorFields
}
}
}
}
}
`
: ""
}
}
posts(first: 3, where: { orderby: { field: DATE, order: DESC } }) {
edges {
node {
...PostFields
}
}
}
}
`,
{
variables: {
id: isDraft ? postPreview.id : slug,
idType: isDraft ? "DATABASE_ID" : "SLUG",
},
},
);
// Draft posts may not have an slug
if (isDraft) data.post.slug = postPreview.id;
// Apply a revision (changes in a published post)
if (isRevision && data.post.revisions) {
const revision = data.post.revisions.edges[0]?.node;
if (revision) Object.assign(data.post, revision);
delete data.post.revisions;
}
// Filter out the main post
data.posts.edges = data.posts.edges.filter(({ node }) => node.slug !== slug);
// If there are still 3 posts, remove the last one
if (data.posts.edges.length > 2) data.posts.edges.pop();
return data;
}
export const EXAMPLE_PATH = "cms-wordpress";
export const CMS_NAME = "WordPress";
export const CMS_URL = "https://wordpress.org";
export const HOME_OG_IMAGE_URL =
"https://og-image.vercel.app/Next.js%20Blog%20Example%20with%20**WordPress**.png?theme=light&md=1&fontSize=75px&images=https%3A%2F%2Fassets.vercel.com%2Fimage%2Fupload%2Ffront%2Fassets%2Fdesign%2Fnextjs-black-logo.svg&images=data%3Aimage%2Fsvg%2Bxml%2C%253C%253Fxml+version%3D%271.0%27+encoding%3D%27UTF-8%27%253F%253E%253Csvg+preserveAspectRatio%3D%27xMidYMid%27+version%3D%271.1%27+viewBox%3D%270+0+256+255%27+xmlns%3D%27http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%27%253E%253Cg+fill%3D%27%2523464342%27%253E%253Cpath+d%3D%27m18.124+127.5c0+43.295+25.161+80.711+61.646+98.441l-52.176-142.96c-6.0691+13.603-9.4699+28.657-9.4699+44.515zm183.22-5.5196c0-13.518-4.8557-22.88-9.0204-30.166-5.5446-9.01-10.742-16.64-10.742-25.65+0-10.055+7.6259-19.414+18.367-19.414+0.48494+0+0.94491+0.060358+1.4174+0.087415-19.46-17.828-45.387-28.714-73.863-28.714-38.213+0-71.832+19.606-91.39+49.302+2.5662+0.077008+4.9847+0.13112+7.039+0.13112+11.441+0+29.151-1.3882+29.151-1.3882+5.8963-0.34758+6.5915+8.3127+0.7014+9.01+0+0-5.9255+0.69724-12.519+1.0427l39.832+118.48+23.937-71.79-17.042-46.692c-5.8901-0.3455-11.47-1.0427-11.47-1.0427-5.8942-0.3455-5.2033-9.3575+0.69099-9.01+0+0+18.064+1.3882+28.811+1.3882+11.439+0+29.151-1.3882+29.151-1.3882+5.9005-0.34758+6.5936+8.3127+0.7014+9.01+0+0-5.938+0.69724-12.519+1.0427l39.528+117.58+10.91-36.458c4.7287-15.129+8.3273-25.995+8.3273-35.359zm-71.921+15.087l-32.818+95.363c9.7988+2.8805+20.162+4.4561+30.899+4.4561+12.738+0+24.953-2.202+36.323-6.2002-0.29346-0.46829-0.55987-0.96572-0.77841-1.5069l-33.625-92.112zm94.058-62.046c0.47037+3.4841+0.73678+7.2242+0.73678+11.247+0+11.1-2.073+23.577-8.3169+39.178l-33.411+96.599c32.518-18.963+54.391-54.193+54.391-94.545+0.002081-19.017-4.8557-36.899-13.399-52.48zm-95.977-75.023c-70.304+0-127.5+57.196-127.5+127.5+0+70.313+57.2+127.51+127.5+127.51+70.302+0+127.51-57.194+127.51-127.51-0.002082-70.304-57.209-127.5-127.51-127.5zm0+249.16c-67.08+0-121.66-54.578-121.66-121.66+0-67.08+54.576-121.65+121.66-121.65+67.078+0+121.65+54.574+121.65+121.65+0+67.084-54.574+121.66-121.65+121.66z%27%2F%253E%253C%2Fg%253E%253C%2Fsvg%253E";
if (!URL.canParse(process.env.WORDPRESS_API_URL)) {
throw new Error(`
Please provide a valid WordPress instance URL.
Add to your environment variables WORDPRESS_API_URL.
`);
}
const { protocol, hostname, port, pathname } = new URL(
process.env.WORDPRESS_API_URL,
);
/** @type {import('next').NextConfig} */
module.exports = {
const nextConfig = {
trailingSlash: true,
images: {
remotePatterns: [
{
protocol: protocol.slice(0, -1),
hostname,
port,
pathname: `${pathname}/**`,
protocol: "http",
hostname: process.env.NEXT_PUBLIC_WORDPRESS_API_HOSTNAME,
port: "",
},
],
},
};
module.exports = nextConfig;
{
"private": true,
"scripts": {
"dev": "next",
"build": "next build",
"dev": "graphql-codegen --config codegen.ts && node ./add-ts-nocheck.js && next dev",
"build": "graphql-codegen --config codegen.ts && node ./add-ts-nocheck.js && next build",
"start": "next start",
"lint": "next lint"
"lint": "next lint",
"codegen": "graphql-codegen --config codegen.ts && node ./add-ts-nocheck.js"
},
"dependencies": {
"@types/node": "^18.6.3",
"@types/react": "^18.0.15",
"@types/react-dom": "^18.0.6",
"classnames": "^2.3.1",
"date-fns": "^2.28.0",
"graphql": "^16.9.0",
"graphql-tag": "^2.12.6",
"next": "latest",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"typescript": "^4.7.4"
"react": "18.3.1",
"react-dom": "18.3.1"
},
"devDependencies": {
"autoprefixer": "10.4.7",
"postcss": "8.4.31",
"tailwindcss": "^3.0.24"
"@graphql-codegen/cli": "5.0.0",
"@graphql-codegen/client-preset": "4.3.3",
"@graphql-codegen/schema-ast": "^4.1.0",
"@types/node": "^20",
"@types/react": "^18",
"@types/react-dom": "^18",
"eslint": "^8",
"eslint-config-next": "latest",
"typescript": "^5"
}
}
import { AppProps } from "next/app";
import "../styles/index.css";
function MyApp({ Component, pageProps }: AppProps) {
return <Component {...pageProps} />;
}
export default MyApp;
import { Html, Head, Main, NextScript } from "next/document";
export default function Document() {
return (
<Html lang="en">
<Head />
<body>
<Main />
<NextScript />
</body>
</Html>
);
}
import { NextApiResponse } from "next";
export default async function exit(_, res: NextApiResponse) {
// Exit Draft Mode by removing the cookie
res.setDraftMode({ enable: false });
// Redirect the user back to the index page.
res.writeHead(307, { Location: "/" });
res.end();
}
import type { NextApiRequest, NextApiResponse } from "next";
import { getPreviewPost } from "../../lib/api";
export default async function preview(
req: NextApiRequest,
res: NextApiResponse,
) {
const { secret, id, slug } = req.query;
// Check the secret and next parameters
// This secret should only be known by this API route
if (
!process.env.WORDPRESS_PREVIEW_SECRET ||
secret !== process.env.WORDPRESS_PREVIEW_SECRET ||
(!id && !slug)
) {
return res.status(401).json({ message: "Invalid token" });
}
// Fetch WordPress to check if the provided `id` or `slug` exists
const post = await getPreviewPost(id || slug, id ? "DATABASE_ID" : "SLUG");
// If the post doesn't exist prevent preview mode from being enabled
if (!post) {
return res.status(401).json({ message: "Post not found" });
}
// Enable Preview Mode by setting the cookies
res.setPreviewData({
post: {
id: post.databaseId,
slug: post.slug,
status: post.status,
},
});
// Redirect to the path from the fetched post
// We don't redirect to `req.query.slug` as that might lead to open redirect vulnerabilities
res.writeHead(307, { Location: `/posts/${post.slug || post.databaseId}` });
res.end();
}
import Head from "next/head";
import { GetStaticProps } from "next";
import Container from "../components/container";
import MoreStories from "../components/more-stories";
import HeroPost from "../components/hero-post";
import Intro from "../components/intro";
import Layout from "../components/layout";
import { getAllPostsForHome } from "../lib/api";
import { CMS_NAME } from "../lib/constants";
export default function Index({ allPosts: { edges }, preview }) {
const heroPost = edges[0]?.node;
const morePosts = edges.slice(1);
return (
<Layout preview={preview}>
<Head>
<title>{`Next.js Blog Example with ${CMS_NAME}`}</title>
</Head>
<Container>
<Intro />
{heroPost && (
<HeroPost
title={heroPost.title}
coverImage={heroPost.featuredImage}
date={heroPost.date}
author={heroPost.author}
slug={heroPost.slug}
excerpt={heroPost.excerpt}
/>
)}
{morePosts.length > 0 && <MoreStories posts={morePosts} />}
</Container>
</Layout>
);
}
export const getStaticProps: GetStaticProps = async ({ preview = false }) => {
const allPosts = await getAllPostsForHome(preview);
return {
props: { allPosts, preview },
revalidate: 10,
};
};
import { useRouter } from "next/router";
import ErrorPage from "next/error";
import Head from "next/head";
import { GetStaticPaths, GetStaticProps } from "next";
import Container from "../../components/container";
import PostBody from "../../components/post-body";
import MoreStories from "../../components/more-stories";
import Header from "../../components/header";
import PostHeader from "../../components/post-header";
import SectionSeparator from "../../components/section-separator";
import Layout from "../../components/layout";
import PostTitle from "../../components/post-title";
import Tags from "../../components/tags";
import { getAllPostsWithSlug, getPostAndMorePosts } from "../../lib/api";
import { CMS_NAME } from "../../lib/constants";
export default function Post({ post, posts, preview }) {
const router = useRouter();
const morePosts = posts?.edges;
if (!router.isFallback && !post?.slug) {
return <ErrorPage statusCode={404} />;
}
return (
<Layout preview={preview}>
<Container>
<Header />
{router.isFallback ? (
<PostTitle>Loading…</PostTitle>
) : (
<>
<article>
<Head>
<title>
{`${post.title} | Next.js Blog Example with ${CMS_NAME}`}
</title>
<meta
property="og:image"
content={post.featuredImage?.node.sourceUrl}
/>
</Head>
<PostHeader
title={post.title}
coverImage={post.featuredImage}
date={post.date}
author={post.author}
categories={post.categories}
/>
<PostBody content={post.content} />
<footer>
{post.tags.edges.length > 0 && <Tags tags={post.tags} />}
</footer>
</article>
<SectionSeparator />
{morePosts.length > 0 && <MoreStories posts={morePosts} />}
</>
)}
</Container>
</Layout>
);
}
export const getStaticProps: GetStaticProps = async ({
params,
preview = false,
previewData,
}) => {
const data = await getPostAndMorePosts(params?.slug, preview, previewData);
return {
props: {
preview,
post: data.post,
posts: data.posts,
},
revalidate: 10,
};
};
export const getStaticPaths: GetStaticPaths = async () => {
const allPosts = await getAllPostsWithSlug();
return {
paths: allPosts.edges.map(({ node }) => `/posts/${node.slug}`) || [],
fallback: true,
};
};
// If you want to use other PostCSS plugins, see the following:
// https://tailwindcss.com/docs/using-with-preprocessors
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
};
<?xml version="1.0" encoding="utf-8"?>
<browserconfig>
<msapplication>
<tile>
<square150x150logo src="/favicons/mstile-150x150.png"/>
<TileColor>#000000</TileColor>
</tile>
</msapplication>
</browserconfig>
<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 20010904//EN"
"http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">
<svg version="1.0" xmlns="http://www.w3.org/2000/svg"
width="1024.000000pt" height="1024.000000pt" viewBox="0 0 1024.000000 1024.000000"
preserveAspectRatio="xMidYMid meet">
<metadata>
Created by potrace 1.11, written by Peter Selinger 2001-2013
</metadata>
<g transform="translate(0.000000,1024.000000) scale(0.100000,-0.100000)"
fill="#000000" stroke="none">
<path d="M4785 10234 c-22 -2 -92 -9 -155 -14 -1453 -131 -2814 -915 -3676
-2120 -480 -670 -787 -1430 -903 -2235 -41 -281 -46 -364 -46 -745 0 -381 5
-464 46 -745 278 -1921 1645 -3535 3499 -4133 332 -107 682 -180 1080 -224
155 -17 825 -17 980 0 687 76 1269 246 1843 539 88 45 105 57 93 67 -8 6 -383
509 -833 1117 l-818 1105 -1025 1517 c-564 834 -1028 1516 -1032 1516 -4 1 -8
-673 -10 -1496 -3 -1441 -4 -1499 -22 -1533 -26 -49 -46 -69 -88 -91 -32 -16
-60 -19 -211 -19 l-173 0 -46 29 c-30 19 -52 44 -67 73 l-21 45 2 2005 3 2006
31 39 c16 21 50 48 74 61 41 20 57 22 230 22 204 0 238 -8 291 -66 15 -16 570
-852 1234 -1859 664 -1007 1572 -2382 2018 -3057 l810 -1227 41 27 c363 236
747 572 1051 922 647 743 1064 1649 1204 2615 41 281 46 364 46 745 0 381 -5
464 -46 745 -278 1921 -1645 3535 -3499 4133 -327 106 -675 179 -1065 223 -96
10 -757 21 -840 13z m2094 -3094 c48 -24 87 -70 101 -118 8 -26 10 -582 8
-1835 l-3 -1798 -317 486 -318 486 0 1307 c0 845 4 1320 10 1343 16 56 51 100
99 126 41 21 56 23 213 23 148 0 174 -2 207 -20z"/>
<path d="M7843 789 c-35 -22 -46 -37 -15 -20 22 13 58 40 52 41 -3 0 -20 -10
-37 -21z"/>
<path d="M7774 744 c-18 -14 -18 -15 4 -4 12 6 22 13 22 15 0 8 -5 6 -26 -11z"/>
<path d="M7724 714 c-18 -14 -18 -15 4 -4 12 6 22 13 22 15 0 8 -5 6 -26 -11z"/>
<path d="M7674 684 c-18 -14 -18 -15 4 -4 12 6 22 13 22 15 0 8 -5 6 -26 -11z"/>
<path d="M7598 644 c-38 -20 -36 -28 2 -9 17 9 30 18 30 20 0 7 -1 6 -32 -11z"/>
</g>
</svg>
{
"name": "Next.js",
"short_name": "Next.js",
"icons": [
{
"src": "/favicons/android-chrome-192x192.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "/favicons/android-chrome-512x512.png",
"sizes": "512x512",
"type": "image/png"
}
],
"theme_color": "#000000",
"background_color": "#000000",
"display": "standalone"
}
import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { print } from "graphql/language/printer";
import { setSeoData } from "@/utils/seoData";
import { fetchGraphQL } from "@/utils/fetchGraphQL";
import { ContentInfoQuery } from "@/queries/general/ContentInfoQuery";
import { ContentNode } from "@/gql/graphql";
import PageTemplate from "@/components/Templates/Page/PageTemplate";
import { nextSlugToWpSlug } from "@/utils/nextSlugToWpSlug";
import PostTemplate from "@/components/Templates/Post/PostTemplate";
import { SeoQuery } from "@/queries/general/SeoQuery";
type Props = {
params: { slug: string };
};
export async function generateMetadata({ params }: Props): Promise<Metadata> {
const slug = nextSlugToWpSlug(params.slug);
const isPreview = slug.includes("preview");
const { contentNode } = await fetchGraphQL<{ contentNode: ContentNode }>(
print(SeoQuery),
{
slug: isPreview ? slug.split("preview/")[1] : slug,
idType: isPreview ? "DATABASE_ID" : "URI",
},
);
if (!contentNode) {
return notFound();
}
const metadata = setSeoData({ seo: contentNode.seo });
return {
...metadata,
alternates: {
canonical: `${process.env.NEXT_PUBLIC_BASE_URL}${slug}`,
},
} as Metadata;
}
export function generateStaticParams() {
return [];
}
export default async function Page({ params }: Props) {
const slug = nextSlugToWpSlug(params.slug);
const isPreview = slug.includes("preview");
const { contentNode } = await fetchGraphQL<{ contentNode: ContentNode }>(
print(ContentInfoQuery),
{
slug: isPreview ? slug.split("preview/")[1] : slug,
idType: isPreview ? "DATABASE_ID" : "URI",
},
);
if (!contentNode) return notFound();
switch (contentNode.contentTypeName) {
case "page":
return <PageTemplate node={contentNode} />;
case "post":
return <PostTemplate node={contentNode} />;
default:
return <p>{contentNode.contentTypeName} not implemented</p>;
}
}
import { draftMode } from "next/headers";
import { NextResponse } from "next/server";
export async function GET(request: Request) {
const { searchParams } = new URL(request.url);
const path = searchParams.get("path");
draftMode().disable();
const response = NextResponse.redirect(
`${process.env.NEXT_PUBLIC_BASE_URL}${path}`,
);
response.headers.set(
"Set-Cookie",
`wp_jwt=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT;`,
);
return response;
}
import { print } from "graphql/language/printer";
import { ContentNode, LoginPayload } from "@/gql/graphql";
import { fetchGraphQL } from "@/utils/fetchGraphQL";
import { draftMode } from "next/headers";
import { NextResponse } from "next/server";
import gql from "graphql-tag";
export const dynamic = "force-dynamic";
export async function GET(request: Request) {
const { searchParams } = new URL(request.url);
const secret = searchParams.get("secret");
const id = searchParams.get("id");
if (secret !== process.env.HEADLESS_SECRET || !id) {
return new Response("Invalid token", { status: 401 });
}
const mutation = gql`
mutation LoginUser {
login( input: {
clientMutationId: "uniqueId",
username: "${process.env.WP_USER}",
password: "${process.env.WP_APP_PASS}"
} ) {
authToken
user {
id
name
}
}
}
`;
const { login } = await fetchGraphQL<{ login: LoginPayload }>(
print(mutation),
);
const authToken = login.authToken;
draftMode().enable();
const query = gql`
query GetContentNode($id: ID!) {
contentNode(id: $id, idType: DATABASE_ID) {
uri
status
databaseId
}
}
`;
const { contentNode } = await fetchGraphQL<{ contentNode: ContentNode }>(
print(query),
{
id,
},
{ Authorization: `Bearer ${authToken}` },
);
if (!contentNode) {
return new Response("Invalid id", { status: 401 });
}
const response = NextResponse.redirect(
`${process.env.NEXT_PUBLIC_BASE_URL}${
contentNode.status === "draft"
? `/preview/${contentNode.databaseId}`
: contentNode.uri
}`,
);
response.headers.set("Set-Cookie", `wp_jwt=${authToken}; path=/;`);
return response;
}
import { NextRequest, NextResponse } from "next/server";
import { revalidatePath, revalidateTag } from "next/cache";
export async function PUT(request: NextRequest) {
const requestBody = await request.text();
const { paths, tags } = requestBody
? JSON.parse(requestBody)
: { paths: [], tags: [] };
let revalidated = false;
if (
request.headers.get("X-Headless-Secret-Key") !== process.env.HEADLESS_SECRET
) {
return NextResponse.json({ message: "Invalid secret" }, { status: 401 });
}
try {
if (paths && Array.isArray(paths) && paths.length > 0) {
Promise.all(paths.map((path) => revalidatePath(path)));
console.log("Revalidated paths:", paths);
revalidated = true;
}
if (tags && Array.isArray(tags) && tags.length > 0) {
Promise.all(tags.map((tag) => revalidateTag(tag)));
console.log("Revalidated tags:", tags);
revalidated = true;
}
return NextResponse.json({
revalidated,
now: Date.now(),
paths,
tags: tags,
});
} catch (error) {
return NextResponse.json(
{ message: "Error revalidating paths or tags" },
{ status: 500 },
);
}
}
* {
box-sizing: border-box;
padding: 0;
margin: 0;
}
html,
body {
max-width: 100vw;
overflow-x: hidden;
}
body {
color: #fff;
background: #000;
}
a {
color: #fff;
text-decoration: underline;
}
import { draftMode } from "next/headers";
import { Inter } from "next/font/google";
import "@/app/globals.css";
import Navigation from "@/components/Globals/Navigation/Navigation";
import { PreviewNotice } from "@/components/Globals/PreviewNotice/PreviewNotice";
const inter = Inter({ subsets: ["latin"] });
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
const { isEnabled } = draftMode();
return (
<html lang="en">
<body className={inter.className}>
{isEnabled && <PreviewNotice />}
<Navigation />
{children}
</body>
</html>
);
}
import type { Metadata } from "next";
import { print } from "graphql/language/printer";
import { setSeoData } from "@/utils/seoData";
import { fetchGraphQL } from "@/utils/fetchGraphQL";
import { ContentNode, Page } from "@/gql/graphql";
import { PageQuery } from "@/components/Templates/Page/PageQuery";
import { SeoQuery } from "@/queries/general/SeoQuery";
const notFoundPageWordPressId = 501;
export async function generateMetadata(): Promise<Metadata> {
const { contentNode } = await fetchGraphQL<{ contentNode: ContentNode }>(
print(SeoQuery),
{ slug: notFoundPageWordPressId, idType: "DATABASE_ID" },
);
const metadata = setSeoData({ seo: contentNode.seo });
return {
...metadata,
alternates: {
canonical: `${process.env.NEXT_PUBLIC_BASE_URL}/404-not-found/`,
},
} as Metadata;
}
export default async function NotFound() {
const { page } = await fetchGraphQL<{ page: Page }>(print(PageQuery), {
id: notFoundPageWordPressId,
});
return <div dangerouslySetInnerHTML={{ __html: page.content || " " }} />;
}
import { MetadataRoute } from "next";
export const revalidate = 0;
export default async function robots(): Promise<MetadataRoute.Robots> {
const res = await fetch(
`${process.env.NEXT_PUBLIC_WORDPRESS_API_URL}/robots.txt`,
{ cache: "no-store" },
);
const text = await res.text();
const lines = text.split("\n");
const userAgent = lines
.find((line) => line.startsWith("User-agent: "))
?.replace("User-agent: ", "");
const allow = lines
.find((line) => line.startsWith("Allow: "))
?.replace("Allow: ", "");
const disallow = lines
.find((line) => line.startsWith("Disallow: "))
?.replace("Disallow: ", "");
const sitemap = lines
.find((line) => line.startsWith("Sitemap: "))
?.replace("Sitemap: ", "");
const robots: MetadataRoute.Robots = {
rules: {
userAgent,
allow,
disallow,
},
sitemap,
};
return robots;
}
import { MetadataRoute } from "next";
export const revalidate = 0;
async function getTotalCounts() {
const response = await fetch(
`${process.env.NEXT_PUBLIC_WORDPRESS_API_URL}/wp-json/sitemap/v1/totalpages`,
);
const data = await response.json();
if (!data) return [];
const propertyNames = Object.keys(data);
const excludeItems = ["page", "user", "category", "tag"];
let totalArray = propertyNames
.filter((name) => !excludeItems.includes(name))
.map((name) => {
return { name, total: data[name] };
});
return totalArray;
}
async function getPostsUrls({
page,
type,
perPage,
}: {
page: number;
type: string;
perPage: number;
}) {
const response = await fetch(
`${process.env.NEXT_PUBLIC_WORDPRESS_API_URL}/wp-json/sitemap/v1/posts?pageNo=${page}&postType=${type}&perPage=${perPage}`,
);
const data = await response.json();
if (!data) return [];
const posts = data.map((post: any) => {
return {
url: `${process.env.NEXT_PUBLIC_BASE_URL}${post.url}`,
lastModified: new Date(post.post_modified_date)
.toISOString()
.split("T")[0],
};
});
return posts;
}
export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
const sitemap = [];
const details = await getTotalCounts();
const postsUrls = await Promise.all(
details.map(async (detail) => {
const { name, total } = detail;
const perPage = 50;
const totalPages = Math.ceil(total / perPage);
const urls = await Promise.all(
Array.from({ length: totalPages }, (_, i) => i + 1).map((page) =>
getPostsUrls({ page, type: name, perPage }),
),
);
return urls.flat();
}),
);
const posts = postsUrls.flat();
sitemap.push(...posts);
return sitemap;
}
.navigation {
padding: 20px;
display: flex;
gap: 20px;
}
import Link from "next/link";
import { print } from "graphql/language/printer";
import styles from "./Navigation.module.css";
import { MenuItem, RootQueryToMenuItemConnection } from "@/gql/graphql";
import { fetchGraphQL } from "@/utils/fetchGraphQL";
import gql from "graphql-tag";
async function getData() {
const menuQuery = gql`
query MenuQuery {
menuItems(where: { location: PRIMARY_MENU }) {
nodes {
uri
target
label
}
}
}
`;
const { menuItems } = await fetchGraphQL<{
menuItems: RootQueryToMenuItemConnection;
}>(print(menuQuery));
if (menuItems === null) {
throw new Error("Failed to fetch data");
}
return menuItems;
}
export default async function Navigation() {
const menuItems = await getData();
return (
<nav
className={styles.navigation}
role="navigation"
itemScope
itemType="http://schema.org/SiteNavigationElement"
>
{menuItems.nodes.map((item: MenuItem, index: number) => {
if (!item.uri) return null;
return (
<Link
itemProp="url"
href={item.uri}
key={index}
target={item.target || "_self"}
>
<span itemProp="name">{item.label}</span>
</Link>
);
})}
</nav>
);
}
.preview {
position: fixed;
top: 0;
right: 0;
left: 0;
margin: 0 auto;
width: 280px;
text-align: center;
max-width: 100%;
border-bottom-left-radius: 5px;
border-bottom-right-radius: 5px;
background-color: #000;
color: #fff;
padding: 5px 15px;
display: flex;
justify-content: space-between;
white-space: nowrap;
}
.link {
margin-left: 10px;
}
"use client";
import styles from "./PreviewNotice.module.css";
import { usePathname } from "next/navigation";
export const PreviewNotice = () => {
const pathname = usePathname();
return (
<aside className={styles.preview}>
Preview mode enabled
<a
className={styles.link}
href={`/api/exit-preview?path=${encodeURIComponent(pathname)}`}
>
Exit
</a>
</aside>
);
};
import gql from "graphql-tag";
export const PageQuery = gql`
query PageQuery($id: ID!, $preview: Boolean = false) {
page(id: $id, idType: DATABASE_ID, asPreview: $preview) {
content
}
}
`;
import { print } from "graphql/language/printer";
import { ContentNode, Page } from "@/gql/graphql";
import { fetchGraphQL } from "@/utils/fetchGraphQL";
import { PageQuery } from "./PageQuery";
interface TemplateProps {
node: ContentNode;
}
export default async function PageTemplate({ node }: TemplateProps) {
const { page } = await fetchGraphQL<{ page: Page }>(print(PageQuery), {
id: node.databaseId,
});
return <div dangerouslySetInnerHTML={{ __html: page?.content || "" }} />;
}
import gql from "graphql-tag";
export const PostQuery = gql`
query PostQuery($id: ID!, $preview: Boolean = false) {
post(id: $id, idType: DATABASE_ID, asPreview: $preview) {
content
date
title
author {
node {
name
}
}
}
}
`;
.post {
max-width: 1000px;
margin: 0 auto;
padding: 30px;
}
.title {
text-align: center;
}
.author {
text-align: center;
color: #666;
margin: 30px 0;
}
import { print } from "graphql/language/printer";
import { ContentNode, Post } from "@/gql/graphql";
import { fetchGraphQL } from "@/utils/fetchGraphQL";
import styles from "./PostTemplate.module.css";
import { PostQuery } from "./PostQuery";
interface TemplateProps {
node: ContentNode;
}
export default async function PostTemplate({ node }: TemplateProps) {
const { post } = await fetchGraphQL<{ post: Post }>(print(PostQuery), {
id: node.databaseId,
});
return (
<div className={styles.post}>
<h1 className={styles.title}>{post.title}</h1>
<div className={styles.author}>By {post.author?.node.name}</div>
<div dangerouslySetInnerHTML={{ __html: post.content || "" }} />
</div>
);
}
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
export async function middleware(request: NextRequest) {
if (!process.env.WP_USER || !process.env.WP_APP_PASS) {
return NextResponse.next();
}
const basicAuth = `${process.env.WP_USER}:${process.env.WP_APP_PASS}`;
const pathNameWithoutTrailingSlash = request.nextUrl.pathname.replace(
/\/$/,
"",
);
const response = await fetch(
`${process.env.NEXT_PUBLIC_WORDPRESS_API_URL}/wp-json/redirection/v1/redirect/?filterBy%5Burl-match%5D=plain&filterBy%5Burl%5D=${pathNameWithoutTrailingSlash}`,
{
headers: {
Authorization: `Basic ${Buffer.from(basicAuth).toString("base64")}`,
"Content-Type": "application/json",
},
},
);
const data = await response.json();
if (data?.items?.length > 0) {
const redirect = data.items.find(
(item: any) => item.url === pathNameWithoutTrailingSlash,
);
if (!redirect) {
return NextResponse.next();
}
const newUrl = new URL(
redirect.action_data.url,
process.env.NEXT_PUBLIC_BASE_URL,
).toString();
return NextResponse.redirect(newUrl, {
status: redirect.action_code === 301 ? 308 : 307,
});
}
}
import gql from "graphql-tag";
export const ContentInfoQuery = gql`
query ContentInfo($slug: ID!, $idType: ContentNodeIdTypeEnum!) {
contentNode(id: $slug, idType: $idType) {
contentTypeName
databaseId
status
uri
}
}
`;
import gql from "graphql-tag";
export const SeoQuery = gql`
query SeoQuery(
$slug: ID!
$idType: ContentNodeIdTypeEnum
$preview: Boolean = false
) {
contentNode(id: $slug, idType: $idType, asPreview: $preview) {
seo {
canonical
cornerstone
focuskw
metaDesc
metaKeywords
metaRobotsNofollow
metaRobotsNoindex
opengraphAuthor
opengraphDescription
opengraphModifiedTime
opengraphPublishedTime
opengraphPublisher
opengraphSiteName
opengraphTitle
opengraphType
opengraphUrl
readingTime
title
twitterDescription
twitterTitle
opengraphImage {
altText
mediaDetails {
height
width
}
sourceUrl
}
twitterImage {
altText
mediaDetails {
width
height
}
sourceUrl
}
}
}
}
`;
import { draftMode, cookies } from "next/headers";
export async function fetchGraphQL<T = any>(
query: string,
variables?: { [key: string]: any },
headers?: { [key: string]: string },
): Promise<T> {
const { isEnabled: preview } = draftMode();
try {
let authHeader = "";
if (preview) {
const auth = cookies().get("wp_jwt")?.value;
if (auth) {
authHeader = `Bearer ${auth}`;
}
}
const body = JSON.stringify({
query,
variables: {
preview,
...variables,
},
});
const response = await fetch(
`${process.env.NEXT_PUBLIC_WORDPRESS_API_URL}/graphql`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
...(authHeader && { Authorization: authHeader }),
...headers,
},
body,
cache: preview ? "no-cache" : "default",
next: {
tags: ["wordpress"],
},
},
);
if (!response.ok) {
console.error("Response Status:", response);
throw new Error(response.statusText);
}
const data = await response.json();
if (data.errors) {
console.error("GraphQL Errors:", data.errors);
throw new Error("Error executing GraphQL query");
}
return data.data;
} catch (error) {
console.error(error);
throw error;
}
}
export const nextSlugToWpSlug = (nextSlug: string) =>
nextSlug && Array.isArray(nextSlug) ? nextSlug.join("/") : nextSlug ?? "/";
import { Page } from "@/gql/graphql";
export const setSeoData = ({ seo }: { seo: Page["seo"] }) => {
if (!seo) return {};
return {
metadataBase: new URL(`${process.env.NEXT_PUBLIC_BASE_URL}`),
title: seo.title || "",
description: seo.metaDesc || "",
robots: {
index: seo.metaRobotsNoindex === "index" ? true : false,
follow: seo.metaRobotsNofollow === "follow" ? true : false,
},
openGraph: {
title: seo.opengraphTitle || "",
description: seo.opengraphDescription || "",
url: seo.opengraphUrl || "",
siteName: seo.opengraphSiteName || "",
images: [
{
url: seo.opengraphImage?.sourceUrl || "",
width: seo.opengraphImage?.mediaDetails?.width || 1200,
height: seo.opengraphImage?.mediaDetails?.height || 630,
alt: seo.opengraphImage?.altText || "",
},
],
locale: "da_DK",
type: seo.opengraphType || "website",
},
twitter: {
card: "summary_large_image",
title: seo.twitterTitle || "",
description: seo.twitterDescription || "",
images: [seo.twitterImage?.sourceUrl || ""],
},
};
};
@tailwind base;
/* Write your own custom base styles here */
/* Start purging... */
@tailwind components;
/* Stop purging. */
/* Write you own custom component styles here */
/* Start purging... */
@tailwind utilities;
/* Stop purging. */
/* Your own custom utilities */
.has-text-align-left {
@apply text-left;
}
.has-text-align-center {
@apply text-center;
}
.has-text-align-right {
@apply text-right;
}
.has-large-font-size {
@apply text-4xl;
}
.alignfull {
@apply w-screen relative;
left: 50%;
margin-left: -50vw;
margin-right: -50vw;
max-width: 100vw;
right: 50%;
}
.wp-block-image img {
@apply max-w-full mt-2;
}
.wp-block-image.aligncenter {
@apply text-center;
}
.wp-block-image.alignfull img,
.wp-block-image.alignwide img {
@apply w-full;
}
.wp-block-image .alignleft,
.wp-block-image .alignright,
.wp-block-image .aligncenter,
.wp-block-image.is-resized {
@apply table ml-0 mr-0;
}
.wp-block-image .alignleft > figcaption,
.wp-block-image .alignright > figcaption,
.wp-block-image .aligncenter > figcaption,
.wp-block-image.is-resized > figcaption {
@apply table-caption;
caption-side: bottom;
}
.wp-block-image .alignleft {
@apply float-left mr-4;
}
.wp-block-image .alignright {
@apply float-right ml-4;
}
.wp-block-image .aligncenter {
@apply m-auto;
}
.wp-block-button a,
.wp-block-file a.wp-block-file__button {
@apply bg-blue-500 text-white no-underline py-2 px-4;
}
.wp-block-button a:hover,
.wp-block-file a.wp-block-file__button:hover {
@apply bg-blue-400 cursor-pointer;
}
.wp-block-file a:first-of-type {
@apply mr-4;
}
.wp-block-cover {
@apply flex flex-wrap justify-center items-center bg-cover bg-center overflow-hidden;
min-height: 430px;
}
.wp-block-verse {
@apply font-sans;
}
.wp-block-media-text {
@apply grid grid-cols-2 gap-4;
}
/** @type {import('tailwindcss').Config} */
module.exports = {
content: [
"./pages/**/*.{js,ts,jsx,tsx}",
"./components/**/*.{js,ts,jsx,tsx}",
],
theme: {
extend: {
colors: {
"accent-1": "#FAFAFA",
"accent-2": "#EAEAEA",
"accent-7": "#333",
success: "#0070f3",
cyan: "#79FFE1",
},
spacing: {
28: "7rem",
},
letterSpacing: {
tighter: "-.04em",
},
lineHeight: {
tight: 1.2,
},
fontSize: {
"5xl": "2.5rem",
"6xl": "2.75rem",
"7xl": "4.5rem",
"8xl": "6.25rem",
},
boxShadow: {
small: "0 5px 10px rgba(0, 0, 0, 0.12)",
medium: "0 8px 30px rgba(0, 0, 0, 0.12)",
},
},
},
plugins: [],
};
......@@ -4,17 +4,24 @@
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": false,
"forceConsistentCasingInFileNames": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "node",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"paths": {
"@/*": ["./src/*"]
}
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
"exclude": ["node_modules"]
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment