How to create a plugin page on the fly

This example shows how to create a page for the plugin on the fly (without creating the real page in DB). For the output of such page will be responsible our php template file. And we no need to create a page in the admin panel for such a page.

To do this, first we need to add an endpoint for the main page.

add_action( 'init', 'add_my_endpoint' );

function add_my_endpoint(){
	add_rewrite_endpoint( 'myplug-page', EP_ROOT );
}

Now, we need to reset the friendly URL rewrites and we will have such working URL:

  • site.com/myplug-page.
  • or site.com/myplug-page/my-query_parameter.

For such a page, it is a good idea to reset the parameters of the main query, so as not to waste resources on a query that we do not use anyway. In this case, the query gets all the latest posts.

You can do it like this:

// truncate the main query for the main page of the site,
// so improve load performance.
add_filter( 'posts_clauses_request', 'skip_main_query_for_myplugpage', 10, 2 );

function skip_main_query_for_myplugpage( $pieces, $wp_query ){

	if( isset( $wp_query->query['myplug-page'] ) && $wp_query->is_main_query() ){
		$pieces['where'] = ' AND ID = 0';
	}

	return $pieces;
}
Create a page template

On a page like is_front_page() we can get the query parameter like this:

$var = get_query_var( 'myplug-page' );

Now let's process the query and include our template file using template_include hook.

add_action( 'template_include', 'myplugpage_template_file', 20 );

function myplugpage_template_file( $template ) {
	global $wp_query;

	// our query
	if ( isset( $wp_query->query['myplug-page'] ) ) {
		$template = __DIR__ . '/path/to/myplug-page-template.php';
	}

	return $template;
}

This Note embeded into: add_rewrite_endpoint()