In a nutshell what I want to achieve is this:
If slug equals foobar
serve the foobar.php
template.
I know I could do this with page-foobar.php
but I don't want to create a page for this.
add_action('init', 'template_suggestions');
function template_suggestions() {
global $wp;
$current_slug = add_query_arg([], $wp->request);
if ($current_slug == 'foobar') {
// No, don't server the 404.php.
// Serve foobar.php.
// But how?
// Big question mark.
}
}
In a nutshell what I want to achieve is this:
If slug equals foobar
serve the foobar.php
template.
I know I could do this with page-foobar.php
but I don't want to create a page for this.
add_action('init', 'template_suggestions');
function template_suggestions() {
global $wp;
$current_slug = add_query_arg([], $wp->request);
if ($current_slug == 'foobar') {
// No, don't server the 404.php.
// Serve foobar.php.
// But how?
// Big question mark.
}
}
Share
Improve this question
edited May 13, 2019 at 19:34
norman.lol
asked Mar 11, 2019 at 12:15
norman.lolnorman.lol
3,2413 gold badges30 silver badges35 bronze badges
1 Answer
Reset to default 1Got it! But this is a dirty thing. As it won't take care of pagination and underlying queries. If you need a bit more of WordPress' logic behind that custom route, please check the answer linked in the comments. But if you just need to serve one static page, this probably is a good starting point:
add_action('template_include', 'template_suggestions');
function template_suggestions($template) {
global $wp;
$current_slug = $wp->request;
$foobar_template = locate_template(['foobar.php']);
if ($current_slug == 'foobar' && $foobar_template != '') {
// Prevent 404.
status_header(200);
return $foobar_template;
}
return $template;
}
Source Don’t use template_redirect to load an alternative template file
Since I use Yoast I had to use wpseo_title
instead of document_title_parts
or pre_get_document_title
to set the title accordingly.
add_filter('wpseo_title', 'template_suggestions_titles', 10, 1);
function template_suggestions_titles() {
global $wp;
$current_slug = $wp->request;
if ($current_slug == 'foobar') {
return 'Foobar';
}
}