diff --git a/lib/plugins/tag/post_link.ts b/lib/plugins/tag/post_link.ts
index 577b1319ef..67289df469 100644
--- a/lib/plugins/tag/post_link.ts
+++ b/lib/plugins/tag/post_link.ts
@@ -10,11 +10,19 @@ import type Hexo from '../../hexo';
*/
export = (ctx: Hexo) => {
return function postLinkTag(args: string[]) {
- const slug = args.shift();
+ let slug = args.shift();
if (!slug) {
throw new Error(`Post not found: "${slug}" doesn't exist for {% post_link %}`);
}
+ let hash = '';
+ const parts = slug.split('#');
+
+ if (parts.length === 2) {
+ slug = parts[0];
+ hash = parts[1];
+ }
+
let escape = args[args.length - 1];
if (escape === 'true' || escape === 'false') {
args.pop();
@@ -33,7 +41,8 @@ export = (ctx: Hexo) => {
const attrTitle = escapeHTML(post.title || post.slug);
if (escape === 'true') title = escapeHTML(title);
- const link = encodeURL(new URL(post.path, ctx.config.url).pathname);
+ const url = new URL(post.path, ctx.config.url).pathname + (hash ? `#${hash}` : '');
+ const link = encodeURL(url);
return `${title}`;
};
diff --git a/test/scripts/tags/post_link.js b/test/scripts/tags/post_link.js
index 999f2cad48..05839a8098 100644
--- a/test/scripts/tags/post_link.js
+++ b/test/scripts/tags/post_link.js
@@ -73,4 +73,8 @@ describe('post_link', () => {
it('should throw if post not found', () => {
should.throw(() => postLink(['bar']), Error, /Post not found: post_link bar\./);
});
+
+ it('should keep hash', () => {
+ postLink(['foo#bar']).should.eql('Hello world');
+ });
});