Created
March 1, 2017 16:17
-
-
Save Ahrengot/95d782f6d7dbfcd2eafdab855dc77dad to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Configure your routes here | |
* Slugs and page titles are translatable | |
*/ | |
$routes = array( | |
"my-profile" => array( | |
"slug" => __( "my-profil" ), | |
"title" => __( "My profile" ) | |
), | |
"login" => array( | |
"slug" => __( "user-login" ), | |
"title" => __( "Log in" ) | |
), | |
"logout" => array( | |
"slug" => __( "user-logout" ), | |
"title" => __( "Log out" ) | |
) | |
); | |
/** | |
* Add endpoints | |
*/ | |
add_action('init', function() use($routes) { | |
foreach ( $routes as $route => $route_opts ) { | |
add_rewrite_rule( | |
sprintf( "^%s/?", $route_opts['slug'] ), | |
sprintf( "index.php?pagename=%s", $route ), | |
'top' | |
); | |
} | |
}); | |
/** | |
* Hook up page templates. | |
*/ | |
add_filter('template_include', function($template) use($routes) { | |
global $wp_query; | |
if ( in_array( get_query_var('pagename'), array_keys($routes) ) ) { | |
// http://wordpress.stackexchange.com/q/228466/23829 | |
$wp_query->is_404 = false; | |
$template = sprintf( | |
// Template files need to match this format: | |
// page-templates/page-*route*.php | |
"%s/page-templates/page-%s.php", | |
get_template_directory(), | |
get_query_var('pagename') | |
); | |
} | |
return $template; | |
}, 10, 1); | |
/** | |
* Add custom page titles | |
*/ | |
add_filter( 'document_title_parts', function($title_arr) use($routes) { | |
foreach ($routes as $route => $route_opts) { | |
if ( get_query_var( 'pagename' ) === $route ) { | |
$title_arr['title'] = $route_opts['title']; | |
} | |
} | |
return $title_arr; | |
}, 10, 1 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment