Reputation: 3131
I have the following JSON data:
[
{
"taxonomy_slug": "product_cat",
"taxonomy_name": "Categories",
"frontend_slug": "product-category"
},
{
"taxonomy_slug": "product_tag",
"taxonomy_name": "Tags",
"frontend_slug": "product-tag"
},
{
"taxonomy_slug": "gift_box_size",
"taxonomy_name": "Gift Box Sizes",
"frontend_slug": "gift_box_size"
},
{
"taxonomy_slug": "product-type",
"taxonomy_name": "Type",
"frontend_slug": "product-type"
}
]
So for each taxonomy front-end slug, I want to generate a page for each taxonomy.
The URLs I want to generate are as follows:
product-category/{category_item_slug}
product-tag/{tag_item_slug}
gift_box_size/{gift_box_size_item_slug}
product-type/{product-type_item_slug}
Now each taxonomy has its own list of items and if it doesn't exist in the Wordpress admin, I want to return 404 page not found.
I have the following file/folder structure
|-> pages
|-> [taxonomy-frontend-slug]
|-> [taxonomy-item-slug].js
[taxonomy-item-slug].js
file
import { useRouter } from 'next/router'
import productTaxonomy from '@gb-data/productTaxonomy.json'
export async function getStaticPaths() {
const paths = productTaxonomy.map((taxonomyData) => {
return {
params: { "taxonomy-frontend-slug": `/${taxonomyData.frontend_slug}` }
}
})
console.log('getStaticPaths', paths)
return {
paths: paths,
fallback: false,
}
}
export async function getStaticProps(context) {
console.log('getStaticProps context', context)
return {
props: {}
}
}
export default function TaxonomyItemPage() {
const router = useRouter()
console.log('router.query', router.query);
return (
<div>
TaxonomyItemPage
</div>
)
}
Upvotes: 0
Views: 231
Reputation: 40909
I see 2 options:
getStaticPaths
. With fallback: false
, users will get 404
for any paths not returned by this function.Something like that should do the trick:
export async function getStaticPaths() {
const taxonomies = await getListOfTaxonomiesFromWordpress();
const paths = taxonomies.map((taxonomyData) => {
return {
params: { "taxonomy-frontend-slug": taxonomyData.frontend_slug }
}
})
return {
paths: paths,
fallback: false,
}
}
getStaticPaths
function like in 1
), return the following from getStaticProps
if data is not available in Wordpress in order to get 404:return {
notFound: true
};
So try the following:
export async function getStaticProps({ params }) {
const taxonomyData = await getTaxonomyDataBySlugFromWordpress(params['taxonomy-frontend-slug']);
if (taxonomyData) {
return {
props: { taxonomyData }
}
}
return {
notFound: true
}
}
Upvotes: 2