0

In a plugin I want to display a specific page without redirecting (and thus without changing the URL) like the plugin https://wordpress.org/plugins/404page/ does. I can capture 404s and redirect them, but I want the URL to stay the same when I show a custom page.

// A. this only displays the content and the not the header, footer, or title.
$post = get_page_by_path('/some-page/');
$content = apply_filters('the_content', $post->post_content);
echo $content;

...

// B. This only displays the page template, but doesn't include the content.
$template = get_template_part('page');
echo $template;

...

// C. A combination of the two doesn't include the sidebar or the or the page title.
$template = get_template_part('header', 'custom-404-page');
echo $template;
$post = get_page_by_path('/custom-page/');
$content = apply_filters('the_content', $post->post_content);
echo $content;
$template = get_template_part('footer', 'custom-404-page');
echo $template;

... I also tried:

// D.
global $post;
$post = get_page_by_path('/custom-404-page/');
setup_postdata($post);
$template = get_template_part('page');
echo $template;

but the content of the page still doesn't appear in the basic page template.

thanks

  • Any reason not to just use add_rewrite_rule()? – Loren Rosen Mar 31 at 18:43
  • I'm not familiar with that but it looks like I would need to know what URL the user requested ahead of time. – Aaron Mar 31 at 19:13
  • You want a different page to be served when they type in a page your plugin is on? Like served normally with nothing different? – tmdesigned Mar 31 at 22:36
  • @tmdesigned That's been my assumption.... – Loren Rosen Mar 31 at 23:51
  • You can use regular expressions in the rewrite rules. So you just need one that matches everything. Something like add_rewrite_rule('.*', 'index.php?pagename=custom-404', 'top'); Note the rewrite rules need to be flushed after this is done, so you would do the add and flush once, when the plugin is activated. Also, this assumes WordPress knows about the page you're redirecting to. – Loren Rosen Mar 31 at 23:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.