Snippets
Custom Routes And URLs
Map fixed URLs to views and keep generated WordPress links aligned
Use these when a route is not a normal WordPress single/archive URL, or when WordPress should generate a custom URL for a post type.
For the full routing docs, see Custom Routes and WordPress Routing.
Fixed Route With A Query Variable
<?php
ED()->addCustomRoute('form/([0-9]+)/?$', [
'template' => 'views/single-form.tsx',
'title' => 'Get in touch',
'queryVars' => [
'formId' => '$1',
],
]);query SingleForm($formId: Int!) {
gravityForm(id: $formId) {
title
}
}Route Slugs Back To A Post ID
Use extraVars when the URL contains slugs but the GraphQL view should receive the resolved WordPress post ID.
<?php
ED()->addCustomRoute('program/event/([a-z0-9-]+)/?$', [
'template' => 'views/single-film.tsx',
'queryVars' => [
'filmSlug' => '$1',
],
'extraVars' => function ($vars) {
global $post;
global $wp_query;
$film = get_page_by_path($vars['filmSlug'], OBJECT, 'film');
if (!$film) return [];
$wp_query->queried_object_id = $film->ID;
$wp_query->queried_object = $film;
$post = $film;
return [
'postId' => $film->ID,
];
},
'is404' => function ($params) {
return empty($params['postId']);
},
]);Generate Matching WordPress URLs
A custom route handles incoming URLs. It does not automatically change URLs generated by WordPress, WPGraphQL, menus, or blocks. Use post_type_link for that.
<?php
ED()->registerPostType('service', [
'label' => 'Services',
'rewrite' => false,
'public' => false,
'show_ui' => true,
'publicly_queryable' => true,
'show_in_graphql' => true,
'graphql_single_name' => 'service',
'graphql_plural_name' => 'services',
]);
add_filter('post_type_link', function ($url, $post) {
if ($post->post_type === 'service') {
return '/services/#' . $post->post_name;
}
return $url;
}, 10, 2);For taxonomy URLs, use the matching WordPress filter, such as term_link.