Posted by

How to create a virtual page in wordpress

There's a lot of ways to create a virtual page in wordpress. And this one would be the simplest method to achieve it.

Just add this in functions.php from the theme that is currently being used in wordpress.

First is to add a query variable which will be used later as identifier.

add_action('query_vars','set_query_var');
function set_query_var($vars) {
  array_push($vars, 'custom_page');
  return $vars;
}

Next is to add a custom rewrite rule, which will tells wordpress to add value to variable custom_page, when desired slug is visited, e.g. domain.com/custom

add_action('init', 'custom_add_rewrite_rule');
function custom_add_rewrite_rule(){
  add_rewrite_rule('^custom$','index.php?custom_page=1','top');
  flush_rewrite_rules(); // ideally, this one should be removed once everything is okay
}

Next is to change what template file to load whenever the variable custom_page is set.

add_filter('template_include', 'plugin_include_template');
function plugin_include_template($template){
  if(get_query_var('custom_page')){
  	$template = get_template_directory() ."/templates/custom.php";
  }    
  return $template;    
}

Then the last thing is to create the file inside the theme that you want to load, e.g [yourtheme]/templates/custom.php

That's it! Happy coding.