In your scenario, where you want to override an auto-generated category page with a manually-created Page in WordPress, especially when using block themes, the challenge arises because block themes use a different file structure compared to classic themes. They rely on HTML templates and theme.json instead of the traditional PHP templates.
Here’s a more elegant solution that’s tailored for block themes:
Use WordPress Rewrite Rules: Instead of using Cloudflare invisible rewrites, you can utilize WordPress’s built-in rewrite rules. This approach will internally redirect requests for the category URL to your custom page URL.
Template Redirect Hook: Use the template_redirect action hook to check if the requested URL is one of your categories that needs to be overridden. If it is, then redirect to the corresponding custom page.
Maintain Block Theme Compatibility: Since block themes don’t use page.php or archive.php, you’ll need to ensure that your redirect points to a URL rather than trying to include a specific template file.
Here’s a basic implementation of this approach:
function wpb_redirect_category_to_page() {
if (is_category('your-category-slug')) {
$page = get_page_by_path('your-custom-page-slug');
if ($page) {
wp_redirect(get_permalink($page->ID));
exit;
}
}
}
add_action('template_redirect', 'wpb_redirect_category_to_page');
Replace ‘your-category-slug’ with the slug of the category you want to override, and ‘your-custom-page-slug’ with the slug of the custom page you want to show instead.
This code checks if the current request is for a specific category, and if so, it redirects to the custom page you’ve created. This should work seamlessly with block themes as it doesn’t rely on specific template files.
Remember to flush your rewrite rules after adding this code. You can do this by visiting the Settings > Permalinks page in your WordPress admin and clicking “Save Changes”.
This approach maintains the integrity of your site’s URL structure and is more in line with WordPress best practices, avoiding the need for external solutions like Cloudflare rewrites.