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 16 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.
25 changes: 24 additions & 1 deletion docs/documentation/01-Getting Started/headless-config.md
Original file line number Diff line number Diff line change
Expand Up @@ -229,4 +229,27 @@ 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 post being previewed 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's link as returned via the WordPress `get_permalink` function.

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
}
}
```

More for info check out the [preview docs](/learn/wordpress-integration/previews#the-usepostlinkforredirect-setting).
60 changes: 57 additions & 3 deletions docs/documentation/06-WordPress Integration/previews.md
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,11 @@ export default async function handler(req, res) {
This option was added in `@headstartwp/[email protected]`.
:::info

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.
:::tip
A better alternative is using `preview.usePostLinkForRedirect`. With this setting, you can set up previews so that it uses the `post.link` property of the post 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/wordpress-integration/previews#the-usepostlinkforredirect-setting).
:::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 is `/%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 All @@ -144,6 +148,56 @@ export default async function handler(req, res) {
}
```

### The `usePostLinkForRedirect` setting

The `preview.usePostLinkForRedirect` was added in `@headstartwp/[email protected]` and it tells the preview handler to use the actual post permalink to figure out where it should redirect to. With this setting, previewing a post will automatically redirect to a route in Next.js based on the permalink structure set in WordPress. As an example let's say you have a custom post type called `news` and its permalink structure is `/news/news-name`. If your Next.js URL structure strictly follows that pattern you would have a route at `pages/news/[...path].js`. Therefore HeadstartWP can infer the proper path to a preview request for a post of type `news`.

This becomes even more useful when you have a more complicated permalink structure, let's say your `news` post type adds the category name to the url such as `/news/political/news-name`. If both your Next.js project and WordPress are following the same permalink structure, no additional logic is required to get previews to work. Previously permalinks like this would require providing custom logic in `getRedirectPath`.

Note that by default, `draft` posts will not have a pretty permalink, instead, they have something like `domain.com/?p=id` so HeadstartWP adds a new rest field for all public post types called: `_tenup_preview_link` which will return a pretty permalink even for draft posts. This field will be used by the previewHandler for draft posts.

If you are overriding permalink in WordPress via filter you must ensure that draft posts have a fallback post name. e.g:

```php
// adds category to the news permalink and prefix it with "newsroom"
add_filter(
'post_type_link',
function ( $post_link, $post ) {
if ( 'news' !== $post->post_type ) {
return $post_link;
}

// draft posts won't have `$post->post_name` set.
$post_name = empty( $post->post_name ) ? sanitize_title( $post->post_title ) : $post->post_name;
$post_name = empty( $post_name ) ? $post->ID : $post_name;

$fallback = esc_url( home_url( sprintf( 'newsroom/%s', $post_name ) ) );

$news_types = wp_get_post_terms( $post->ID, 'category', [ 'fields' => 'slugs' ] );

if (
is_wp_error( $news_types ) ||
! is_array( $news_types ) ||
! count( $news_types ) > 0
) {
return $fallback;
}

return esc_url( home_url( sprintf( 'newsroom/%s/%s', $news_types[0], $post_name ) ) );
},
10,
2
);
```

You can also use a placeholder instead of manually handling post_name yourself e.g:

```php
$post_name = empty( $post->post_name ) ? '%postname%' : $post->post_name;
```

When building the permalink for draft posts the framework will automatically replace `%postname` or `%pagename%` with the post_name (based on the title) or a fallback to post id.

## FAQ

**After a while, the preview URL stops working**
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 true', async () => {
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 },
});
});
17 changes: 15 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,19 @@ export async function previewHandler(
* @returns the default redirec tpath
*/
const getDefaultRedirectPath = () => {
if (preview?.usePostLinkForRedirect) {
if (
result.status === 'draft' &&
typeof result._tenup_preview_link === 'undefined'
) {
throw new Error(
'You are using usePostLinkForRedirect setting but your rest response does not have _tenup_preview_link, ensure you are running the latest version of the plugin',
);
}
const link = result._tenup_preview_link ?? result.link;
return removeSourceUrl({ link: link as string, 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,
},
};
62 changes: 62 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,68 @@ class PreviewLink {
*/
public function register() {
add_filter( 'template_include', [ $this, 'handle_preview' ], 20 );

// only add _tenup_preview_link for preview authenticated requests
if ( PreviewToken::get_payload_from_token() ) {
add_action( 'rest_api_init', [ $this, 'add_preview_link_field' ] );
}
}

/**
* Adds preview link field
*
* @return void
*/
public function add_preview_link_field() {
$post_types = get_post_types( [ 'show_in_rest' => true ], 'names' );

foreach ( $post_types as $post_type ) {
register_rest_field(
$post_type,
'_tenup_preview_link',
[
'get_callback' => function ( $post_object ) {
return $this->get_draft_permalink( get_post( $post_object['id'] ) );
},
'schema' => [
'type' => 'string',
],
]
);
}
}

/**
* Get drafts permalinks
*
* @param \WP_Post $post The post in question.
*
* @return string
*/
public function get_draft_permalink( \WP_Post $post ): string {
try {
$payload = PreviewToken::get_payload_from_token();

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

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 '';
} catch ( \Exception $e ) {
return '';
}
}

/**
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