To create subpages like /location/berlin/visit, /location/berlin/hotels, and /location/berlin/about for each of your custom post types, you need to use WordPress rewrite rules and possibly custom query variables. This approach allows you to handle custom URL structures and associate them with your custom post type "location".
Here's a step-by-step guide to achieve this:
Step 1: Define Custom Rewrite Rules
You need to add custom rewrite rules to handle your new URL structure. This can be done by hooking into the init action and using the add_rewrite_rule function.
function wpb_add_custom_rewrite_rules() {
add_rewrite_rule(
'^location/([^/]+)/([^/]+)/?$',
'index.php?location=$matches[1]&wpb_location_page=$matches[2]',
'top'
);
}
add_action('init', 'wpb_add_custom_rewrite_rules');
In this rule, ^location/([^/]+)/([^/]+)/?$ is a regular expression that matches URLs of the format /location/{location-name}/{subpage}/. The location and wpb_location_page are query variables that will be used to determine the actual content to display.
Step 2: Add Custom Query Variables
You need to let WordPress know about the new query variable wpb_location_page.
function wpb_add_query_vars($vars) {
$vars[] = 'wpb_location_page';
return $vars;
}
add_filter('query_vars', 'wpb_add_query_vars');
Step 3: Handle The Custom Query
Now, you need to hook into the template redirect action to handle these custom queries and serve the appropriate content.
function wpb_location_template_redirect() {
$location = get_query_var('location');
$location_page = get_query_var('wpb_location_page');
if ($location && $location_page) {
// Load your custom template or perform any logic here
// For example:
include(get_stylesheet_directory() . '/location-subpage.php');
exit;
}
}
add_action('template_redirect', 'wpb_location_template_redirect');
Step 4: Flush Rewrite Rules
After adding these codes, remember to flush your rewrite rules. You can do this by visiting the Permalinks settings page in the WordPress admin and simply clicking "Save Changes".
Optional: Creating the Subpage Content
The actual content of the subpages (e.g., visit, hotels, about) can be handled in various ways, depending on your specific requirements. You might use custom fields, create a taxonomy for subpage types, or even hard-code the content in the template files. This part is quite flexible and depends on how you want to manage and display these subpages.