Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: post.link #712

Merged
merged 17 commits into from
Mar 11, 2024
Merged
Show file tree
Hide file tree
Changes from 11 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .changeset/poor-wolves-repeat.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
"@headstartwp/headstartwp": patch
"@headstartwp/core": patch
"@headstartwp/next": patch
---

Add the ability to leverage `post.link` for redirecting the previewed post to the appropriate route via the `preview.usePostLinkForRedirect` setting.
21 changes: 21 additions & 0 deletions docs/documentation/01-Getting Started/headless-config.md
Original file line number Diff line number Diff line change
Expand Up @@ -229,4 +229,25 @@ module.exports = {
alternativeAuthorizationHeader: true
}
}
```

### usePostLinkForRedirect

:::info
This feature was added in `@headstartwp/[email protected]` and requires the plugin version >= 1.1.2.
:::info

This option, if enabled, will use the `post.link` property of the REST response to redirect to the appropriate route for previewing. This can be very useful to avoid the need for providing a custom [getRedirectPath](/learn/wordpress-integration/previews#getredirectpath) implementation by telling the preview handler to simply use the `post.link` property coming in via the REST API response for the previewed post.

Note that you will want to make sure that your WordPress permalink structure closely follows the route structure of your Next.js app for this option to work well.

```js
module.exports = {
// other configs.
// ...

preview: {
usePostLinkForRedirect: true
}
}
```
8 changes: 6 additions & 2 deletions docs/documentation/06-WordPress Integration/previews.md
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,10 @@ export default async function handler(req, res) {
This option was added in `@headstartwp/[email protected]`.
:::info

:::tip
A better alternative is using `preview.usePostLinkForRedirect`. With this setting, you can set up previews so that it uses the `link` property returned in the REST API response for redirecting to the appropriate path/route. This requires that your WordPress permalink matches the Next.js route structure. Check out the docs for [preview.usePostLinkForRedirect](/learn/getting-started/headless-config/#usepostlinkforredirect).
:::tip

The `getRedirectPath` option allows you to customize the redirected URL that should handle the preview request. This can be useful if you have implemented a non-standard URL structure. For instance, if the permalink for your posts are `/%category%/%postname%/` you could create a `/src/pages/[category]/[...path.js]` route to handle single post. However, once you do that the `previewHandler` doesn't know how to redirect to that URL and as such you will have to provide your own redirect handling.

The framework will also use this value to restrict the preview cookie to the post being previewed to avoid bypassing `getStaticProps` until the cookie expires or the browser is closed. See the [Next.js docs](https://nextjs.org/docs/pages/building-your-application/configuring/preview-mode#specify-the-preview-mode-duration) for more info.
Expand Down Expand Up @@ -120,10 +124,10 @@ export default async function handler(req, res) {

#### `onRedirect`

:::caution
:::tip
Instead of implementing `onRedirect` we recommend implementing `getRedirectPath` instead as that will only enable the preview cookie for
the post being previewed.
:::caution
:::tip

The `onRedirect` gives you full access to the `req` and `res` objects. If you do need implement this function we recommend also implementing `getRedirectPath`.

Expand Down
6 changes: 6 additions & 0 deletions packages/core/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,12 @@ export type PreviewConfig = {
* This can be useful if you have separate JWT-based authentication on your project.
*/
alternativeAuthorizationHeader?: boolean;

/**
* If enabled, it will use the `post.link` property of the REST response
* to redirect to the appropriate route for previewing
*/
usePostLinkForRedirect?: boolean;
};

export type HeadlessConfig = {
Expand Down
30 changes: 29 additions & 1 deletion packages/next/src/handlers/__tests__/previewHandler.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { createMocks } from 'node-mocks-http';
import { DRAFT_POST_ID, VALID_AUTH_TOKEN } from '@headstartwp/core/test';
import { setHeadstartWPConfig } from '@headstartwp/core';
import { removeSourceUrl, setHeadstartWPConfig } from '@headstartwp/core';
import { previewHandler } from '../previewHandler';

describe('previewHandler', () => {
Expand Down Expand Up @@ -284,4 +284,32 @@ describe('previewHandler', () => {
'Cannot preview an unknown post type, did you forget to add it to headless.config.js?',
);
});

it('use post.link when preview.usePostLinkForRedirect is treu', async () => {
nicholasio marked this conversation as resolved.
Show resolved Hide resolved
setHeadstartWPConfig({
preview: { usePostLinkForRedirect: true },
});

const { req, res } = createMocks({
method: 'GET',
query: { post_id: DRAFT_POST_ID, token: VALID_AUTH_TOKEN, post_type: 'post' },
});

res.setPreviewData = jest.fn();
await previewHandler(req, res);

expect(res.setPreviewData).toHaveBeenCalled();
expect(res._getStatusCode()).toBe(302);

// instead of manually building the redirect url it should just use what's coming from post.link
// manually calling removeSourceUrl here bc currently test suite doesn't have any source url set so it can't
// do link replacement automatically
expect(
removeSourceUrl({ link: res._getRedirectUrl(), backendUrl: 'https://js1.10up.com' }),
).toBe('/2020/05/07/modi-qui-dignissimos-sed-assumenda-sint-iusto-preview=true');
});

setHeadstartWPConfig({
preview: { usePostLinkForRedirect: false },
});
});
8 changes: 6 additions & 2 deletions packages/next/src/handlers/previewHandler.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/* eslint-disable consistent-return */
import { CustomPostType, getSiteByHost, PostEntity } from '@headstartwp/core';
import { CustomPostType, getSiteByHost, PostEntity, removeSourceUrl } from '@headstartwp/core';
import { getCustomPostType, getHeadstartWPConfig } from '@headstartwp/core/utils';
import type { NextApiRequest, NextApiResponse } from 'next';
import { fetchHookData, usePost } from '../data';
Expand Down Expand Up @@ -177,7 +177,7 @@ export async function previewHandler(

const id = Number(post_id);

const result = Array.isArray(data?.result) ? data.result[0] : data.result;
const result: PostEntity = Array.isArray(data?.result) ? data.result[0] : data.result;

if (result?.id === id || result?.parent === id) {
const { slug } = result;
Expand All @@ -199,6 +199,10 @@ export async function previewHandler(
* @returns the default redirec tpath
*/
const getDefaultRedirectPath = () => {
if (preview?.usePostLinkForRedirect) {
return removeSourceUrl({ link: result.link, backendUrl: sourceUrl ?? '' });
}

const singleRoute = postTypeDef.single || '/';
// remove leading slashes
const prefixRoute = singleRoute.replace(/^\/+/, '');
Expand Down
8 changes: 8 additions & 0 deletions projects/wp-nextjs/headstartwp.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -55,4 +55,12 @@ module.exports = {
*/
devMode: process.env?.ENABLE_DEV_MODE === 'true',
},

preview: {
/**
* If enabled, it will use the `post.link` property of the REST response
* to redirect to the appropriate route for previewing
*/
usePostLinkForRedirect: true,
},
};
90 changes: 90 additions & 0 deletions wp/headless-wp/includes/classes/Preview/PreviewLink.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,96 @@ class PreviewLink {
*/
public function register() {
add_filter( 'template_include', [ $this, 'handle_preview' ], 20 );

add_filter( 'post_link', [ $this, 'force_posts_drafts_to_have_permalinks' ], 10, 2 );
add_filter( 'post_type_link', [ $this, 'force_cpts_drafts_to_have_permalinks' ], 10, 2 );
add_action( 'page_link', [ $this, 'force_page_drafts_to_have_permalinks' ], 10, 2 );
Copy link
Contributor

@lucymtc lucymtc Mar 9, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

will this have any impact if usePostLinkForRedirect is false? should this logic be optional?

Just thinking In a client-project we filter post_type_link to have a structure with taxonomy in it, we had to add a check on the empty post name to not filter the link on drafts as preview would break.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it would be a interesting use case to test. This code uses get_sample_permalink which still calls get_permalink so it would catch the changes you would have made for cpts.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've reworked things a bit. I'm returning the draft permalink via a new rest field that only gets used when the settting is enabled on the framework.

Therefore it won't cause any breakages in existing code. I've also added a test for a usecase like you mentioned and as you can see it works fine as long as you default post name to something.

I'll also update docs with best pratices for making this change work with custom permalinks like you mentioned

}

/**
* Force drafts to have permalinks
*
* @param string $permalink The post's permalink.
* @param \WP_Post $post The post in question.
*
* @return string
*/
protected function force_drafts_to_have_permalinks( string $permalink, \WP_Post $post ): string {
if ( 'draft' !== $post->post_status ) {
return $permalink;
}

try {
$payload = PreviewToken::get_payload_from_token();

if ( ! $payload ) {
return $permalink;
}

if ( 'preview' === $payload->type && $post->ID === $payload->post_id ) {
if ( ! function_exists( 'get_sample_permalink' ) ) {
include_once ABSPATH . 'wp-admin/includes/post.php';
}

[$permastruct, $post_name] = \get_sample_permalink( $post->ID );
$link = str_replace( '%postname%', $post_name, $permastruct );
$link = str_replace( '%pagename%', $post_name, $link );

return $link;
}

return $permalink;
} catch ( \Exception $e ) {
return $permalink;
}
}

/**
* Force posts drafts to have permalinks
*
* @param string $permalink The post's permalink.
* @param \WP_Post $post The post in question.
*
* @return string
*/
public function force_posts_drafts_to_have_permalinks( string $permalink, \WP_Post $post ): string {
remove_filter( 'post_link', [ $this, 'force_posts_drafts_to_have_permalinks' ], 10, 2 );
$link = $this->force_drafts_to_have_permalinks( $permalink, $post );
add_filter( 'post_link', [ $this, 'force_posts_drafts_to_have_permalinks' ], 10, 2 );

return $link;
}

/**
* Force cpts drafts to have permalinks
*
* @param string $permalink The post's permalink.
* @param \WP_Post $post The post in question.
*
* @return string
*/
public function force_cpts_drafts_to_have_permalinks( string $permalink, \WP_Post $post ): string {
remove_filter( 'post_type_link', [ $this, 'force_cpts_drafts_to_have_permalinks' ], 10, 2 );
$link = $this->force_drafts_to_have_permalinks( $permalink, $post );
add_filter( 'post_type_link', [ $this, 'force_cpts_drafts_to_have_permalinks' ], 10, 2 );

return $link;
}

/**
* Force page drafts to have permalinks
*
* @param string $permalink The post's permalink.
* @param int $page_id The page_id
*
* @return string
*/
public function force_page_drafts_to_have_permalinks( string $permalink, int $page_id ): string {
remove_filter( 'page_link', [ $this, 'force_page_drafts_to_have_permalinks' ], 10, 2 );
$link = $this->force_drafts_to_have_permalinks( $permalink, get_post( $page_id ) );
add_filter( 'page_link', [ $this, 'force_page_drafts_to_have_permalinks' ], 10, 2 );

return $link;
}

/**
Expand Down
1 change: 1 addition & 0 deletions wp/headless-wp/includes/classes/Redirect.php
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ public function maybe_redirect_frontend() {
// if any sitemap requests reaches this point then it is a 404
if ( str_contains( $url_request, 'sitemap' ) && str_ends_with( $url_request, '.xml' ) ) {
// redirect to the homepage, otherwise users would see a HTTP 404 (not the 404 page on next.js) error on the browser.
// phpcs:ignore WordPress.Security.SafeRedirect.wp_redirect_wp_redirect
\wp_redirect( trailingslashit( esc_url_raw( $site_url ) ), 307 );
exit;
}
Expand Down
Loading
Loading