Skip to content
This repository was archived by the owner on Feb 27, 2024. It is now read-only.

Commit 506386b

Browse files
committed
Add post preview handling in static props
1 parent e6bbd66 commit 506386b

File tree

1 file changed

+27
-8
lines changed

1 file changed

+27
-8
lines changed

api/wordpress/_global/getPostTypeStaticProps.js

Lines changed: 27 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -8,15 +8,17 @@ import getFrontendPage, {frontendPageSeo} from './getFrontendPage'
88
* Retrieve static props by post type.
99
*
1010
* @author WebDevStudios
11-
* @param {string} params Post params (e.g., slug).
12-
* @param {string} postType Post Type.
13-
* @return {object} Object containing post props and revalidate setting.
11+
* @param {string} params Post params (e.g., slug).
12+
* @param {string} postType Post Type.
13+
* @param {boolean} preview Whether requesting preview of post.
14+
* @param {object} previewData Post preview data.
15+
* @return {object} Object containing post props and revalidate setting.
1416
*/
1517
export default async function getPostTypeStaticProps(
1618
params,
17-
postType
18-
// preview = false, // TODO - add preview handling.
19-
// previewData = null
19+
postType,
20+
preview = false,
21+
previewData = null
2022
) {
2123
// Set revalidate length (seconds).
2224
const revalidate = 60 * 5
@@ -59,16 +61,33 @@ export default async function getPostTypeStaticProps(
5961
// Handle catch-all routes.
6062
const slug = Array.isArray(params.slug) ? params.slug.join('/') : params.slug
6163

64+
// Get post identifier (ID or slug).
65+
const postId = Number.isInteger(Number(slug)) ? Number(slug) : slug
66+
67+
// Check if preview mode is active and valid for current post (preview and post IDs or slugs match).
68+
const isCurrentPostPreview =
69+
preview &&
70+
(postId === previewData?.post?.id || postId === previewData?.post?.slug)
71+
72+
// Check if viewing a draft post.
73+
const isDraft = isCurrentPostPreview && 'draft' === previewData?.post?.status
74+
75+
// Set query variables.
76+
const id = isDraft ? previewData.post.id : slug
77+
const idType = isDraft ? 'DATABASE_ID' : 'SLUG'
78+
6279
// Retrieve post data.
6380
const {apolloClient, error, ...postData} = await getPostTypeById(
6481
postType,
65-
slug
82+
id,
83+
idType
6684
)
6785

6886
const props = {
6987
...postData,
7088
...sharedProps,
71-
error
89+
error,
90+
preview: isCurrentPostPreview
7291
}
7392

7493
// Custom handling for homepage.

0 commit comments

Comments
 (0)