How to create a virtual page in wordpress

How to create a virtual page in wordpress

Everytime I have a wordpress project, this feature seems always present and I always had to search it in google LOL. So I decided to write a post about it because there's a bunch of code I found and have tested that aren't working on my end which consumed my time.

I think the code explain itself so just play with it in your functions.php.

//1. add a wp query variable to redirect to
function set_query_var($vars) {
  array_push($vars, 'custom_page'); // ref url redirected to in add rewrite rule
  return $vars;

//2. Create a redirect
add_action('init', 'custom_add_rewrite_rule');
function custom_add_rewrite_rule(){
  //flush the rewrite rules, should be in a plugin activation hook, i.e only run once...

//3.return the file we want...
add_filter('template_include', 'plugin_include_template');
function plugin_include_template($template){
  	$template = get_template_directory() ."/templates/custom.php";
  return $template;    

After putting the code above create the file custom.php inside a folder named "templates" in your theme (you may changed it to your liking).

Now visit your page and you'll see that it's no longer relying on a wordpress page.

This snippet come from David who gives an answer at stackoverflow.

Tagged with