fix: lang switch
All checks were successful
Build & Deploy / 🔍 Prepare (push) Successful in 6s
Build & Deploy / 🧪 QA (push) Successful in 2m14s
Build & Deploy / 🏗️ Build (push) Successful in 3m24s
Build & Deploy / 🚀 Deploy (push) Successful in 16s
Build & Deploy / 🧪 Post-Deploy Verification (push) Successful in 42m44s
Build & Deploy / 🔔 Notify (push) Successful in 2s
All checks were successful
Build & Deploy / 🔍 Prepare (push) Successful in 6s
Build & Deploy / 🧪 QA (push) Successful in 2m14s
Build & Deploy / 🏗️ Build (push) Successful in 3m24s
Build & Deploy / 🚀 Deploy (push) Successful in 16s
Build & Deploy / 🧪 Post-Deploy Verification (push) Successful in 42m44s
Build & Deploy / 🔔 Notify (push) Successful in 2s
This commit is contained in:
35
lib/blog.ts
35
lib/blog.ts
@@ -59,7 +59,8 @@ export async function getPostBySlug(slug: string, locale: string): Promise<PostD
|
||||
try {
|
||||
const payload = await getPayload({ config: configPromise });
|
||||
|
||||
const { docs } = await payload.find({
|
||||
// First try: Find in the requested locale
|
||||
let { docs } = await payload.find({
|
||||
collection: 'posts',
|
||||
where: {
|
||||
slug: { equals: slug },
|
||||
@@ -70,6 +71,38 @@ export async function getPostBySlug(slug: string, locale: string): Promise<PostD
|
||||
limit: 1,
|
||||
});
|
||||
|
||||
// Fallback: If not found, try searching across all locales.
|
||||
// This happens when a user uses the static language switcher
|
||||
// e.g. switching from /en/blog/en-slug to /de/blog/en-slug.
|
||||
if (!docs || docs.length === 0) {
|
||||
const { docs: crossLocaleDocs } = await payload.find({
|
||||
collection: 'posts',
|
||||
where: {
|
||||
slug: { equals: slug },
|
||||
...(!config.showDrafts ? { _status: { equals: 'published' } } : {}),
|
||||
},
|
||||
locale: 'all',
|
||||
draft: config.showDrafts,
|
||||
limit: 1,
|
||||
});
|
||||
|
||||
if (crossLocaleDocs && crossLocaleDocs.length > 0) {
|
||||
// Fetch the found document again, but strictly in the requested locale
|
||||
// so we get the correctly translated fields (like the localized slug)
|
||||
const { docs: correctLocaleDocs } = await payload.find({
|
||||
collection: 'posts',
|
||||
where: {
|
||||
id: { equals: crossLocaleDocs[0].id },
|
||||
},
|
||||
locale: locale as any,
|
||||
draft: config.showDrafts,
|
||||
limit: 1,
|
||||
});
|
||||
|
||||
docs = correctLocaleDocs;
|
||||
}
|
||||
}
|
||||
|
||||
if (!docs || docs.length === 0) return null;
|
||||
|
||||
const doc = docs[0];
|
||||
|
||||
Reference in New Issue
Block a user