最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Prevent 404 and serve custom template for custom URL

programmeradmin1浏览0评论

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
Add a comment  | 

1 Answer 1

Reset to default 1

Got 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';
  }
}
发布评论

评论列表(0)

  1. 暂无评论