// Tag Redirect Script for Ghost CMS
// This will redirect paths like /weeknote to the latest post with the corresponding tag
// Main configuration
const ghostConfig = {
// Content API key from your Ghost site
contentApiKey: '533db792a70d450ac8dcae8dff',
// Path to tag mapping
pathMappings: {
'/weeknote': 'weeknote',
'/weeknotes': 'weeknote', // Support plural version too
'/newsletter': 'newsletter'
// Add more as needed
}
};
// Only run on paths we want to redirect
document.addEventListener('DOMContentLoaded', function() {
// Clean up the path (handle trailing slashes and query params)
const currentPath = window.location.pathname.split('?')[0];
const cleanPath = currentPath.endsWith('/') ? currentPath.slice(0, -1) : currentPath;
// Get the tag slug corresponding to this path
const tagSlug = ghostConfig.pathMappings[cleanPath];
// Only proceed if this path should be redirected
if (!tagSlug) {
return;
}
// Show loading indicator
const loadingEl = document.createElement('div');
loadingEl.style.cssText = 'position:fixed; top:0; left:0; right:0; bottom:0; background:white; z-index:9999; display:flex; align-items:center; justify-content:center; flex-direction:column; font-family:system-ui,-apple-system,sans-serif;';
loadingEl.innerHTML = `
Finding the latest ${tagSlug}...
Please wait
`;
document.body.appendChild(loadingEl);
// Build the API URL - use absolute URL with the current domain
const apiHost = window.location.origin;
const apiUrl = `${apiHost}/ghost/api/content/posts/?key=${ghostConfig.contentApiKey}&filter=tag:${tagSlug}&limit=1&order=published_at%20desc&fields=url`;
console.log(`Fetching latest ${tagSlug} post from: ${apiUrl}`);
// Make the API request
fetch(apiUrl)
.then(response => {
if (!response.ok) {
throw new Error(`API request failed with status ${response.status}`);
}
return response.json();
})
.then(data => {
if (data.posts && data.posts.length > 0) {
// Found a post - redirect to it
const postUrl = data.posts[0].url;
console.log(`Redirecting to: ${postUrl}`);
window.location.href = postUrl;
} else {
// No posts found
showErrorMessage(`No posts with the "${tagSlug}" tag were found.`);
}
})
.catch(error => {
console.error('Error fetching posts:', error);
showErrorMessage(`Sorry, we couldn't find the latest ${tagSlug}. (${error.message})`);
});
// Helper function to show error messages
function showErrorMessage(message) {
loadingEl.innerHTML = `
Oops!
${message}
Return to homepage
`;
}
});