Skip to content

Instantly share code, notes, and snippets.

@gmazzap
Last active April 22, 2024 12:08
Show Gist options
  • Star 57 You must be signed in to star a gist
  • Fork 15 You must be signed in to fork a gist
  • Save gmazzap/1efe17a8cb573e19c086 to your computer and use it in GitHub Desktop.
Save gmazzap/1efe17a8cb573e19c086 to your computer and use it in GitHub Desktop.
WordPress plugin to ease the creation of virtual pages.
<?php
namespace GM\VirtualPages;
/**
* @author Giuseppe Mazzapica <giuseppe.mazzapica@gmail.com>
* @license http://opensource.org/licenses/MIT MIT
*/
class Controller implements ControllerInterface {
private $pages;
private $loader;
private $matched;
function __construct( TemplateLoaderInterface $loader ) {
$this->pages = new \SplObjectStorage;
$this->loader = $loader;
}
function init() {
do_action( 'gm_virtual_pages', $this );
}
function addPage( PageInterface $page ) {
$this->pages->attach( $page );
return $page;
}
function dispatch( $bool, \WP $wp ) {
if ( $this->checkRequest() && $this->matched instanceof Page ) {
$this->loader->init( $this->matched );
$wp->virtual_page = $this->matched;
do_action( 'parse_request', $wp );
$this->setupQuery();
do_action( 'wp', $wp );
$this->loader->load();
$this->handleExit();
}
return $bool;
}
private function checkRequest() {
$this->pages->rewind();
$path = trim( $this->getPathInfo(), '/' );
while( $this->pages->valid() ) {
if ( trim( $this->pages->current()->getUrl(), '/' ) === $path ) {
$this->matched = $this->pages->current();
return TRUE;
}
$this->pages->next();
}
}
private function getPathInfo() {
$home_path = parse_url( home_url(), PHP_URL_PATH );
return preg_replace( "#^/?{$home_path}/#", '/', add_query_arg( array() ) );
}
private function setupQuery() {
global $wp_query;
$wp_query->init();
$wp_query->is_page = TRUE;
$wp_query->is_singular = TRUE;
$wp_query->is_home = FALSE;
$wp_query->found_posts = 1;
$wp_query->post_count = 1;
$wp_query->max_num_pages = 1;
$posts = (array) apply_filters(
'the_posts', array( $this->matched->asWpPost() ), $wp_query
);
$post = $posts[0];
$wp_query->posts = $posts;
$wp_query->post = $post;
$wp_query->queried_object = $post;
$GLOBALS['post'] = $post;
$wp_query->virtual_page = $post instanceof \WP_Post && isset( $post->is_virtual )
? $this->matched
: NULL;
}
public function handleExit() {
exit();
}
}
<?php
namespace GM\VirtualPages;
/**
* @author Giuseppe Mazzapica <giuseppe.mazzapica@gmail.com>
* @license http://opensource.org/licenses/MIT MIT
*/
interface ControllerInterface {
/**
* Init the controller, fires the hook that allow consumer to add pages
*/
function init();
/**
* Register a page object in the controller
*
* @param \GM\VirtualPages\Page $page
* @return \GM\VirtualPages\Page
*/
function addPage( PageInterface $page );
/**
* Run on 'do_parse_request' and if the request is for one of the registerd
* setup global variables, fire core hooks, requires page template and exit.
*
* @param boolean $bool The boolean flag value passed by 'do_parse_request'
* @param \WP $wp The global wp object passed by 'do_parse_request'
*/
function dispatch( $bool, \WP $wp );
}
<?php namespace GM\VirtualPages;
/*
Plugin Name: GM Virtual Pages
Plugin URI: http://wordpress.stackexchange.com/questions/162240/custom-pages-with-plugin
Description: Virtual pages made easy.
Author: Giuseppe Mazzapica
Author URI: http://gm.zoomlab.it
License: MIT
*/
require_once 'PageInterface.php';
require_once 'ControllerInterface.php';
require_once 'TemplateLoaderInterface.php';
require_once 'Page.php';
require_once 'Controller.php';
require_once 'TemplateLoader.php';
$controller = new Controller ( new TemplateLoader );
add_action( 'init', array( $controller, 'init' ) );
add_filter( 'do_parse_request', array( $controller, 'dispatch' ), PHP_INT_MAX, 2 );
add_action( 'loop_end', function( \WP_Query $query ) {
if ( isset( $query->virtual_page ) && ! empty( $query->virtual_page ) ) {
$query->virtual_page = NULL;
}
} );
add_filter( 'the_permalink', function( $plink ) {
global $post, $wp_query;
if (
$wp_query->is_page
&& isset( $wp_query->virtual_page )
&& $wp_query->virtual_page instanceof Page
&& isset( $post->is_virtual )
&& $post->is_virtual
) {
$plink = home_url( $wp_query->virtual_page->getUrl() );
}
return $plink;
} );
The MIT License (MIT)
Copyright (c) 2016 Giuseppe Mazzapica
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
<?php
namespace GM\VirtualPages;
/**
* @author Giuseppe Mazzapica <giuseppe.mazzapica@gmail.com>
* @license http://opensource.org/licenses/MIT MIT
*/
class Page implements PageInterface {
private $url;
private $title;
private $content;
private $template;
private $wp_post;
function __construct( $url, $title = 'Untitled', $template = 'page.php' ) {
$this->url = filter_var( $url, FILTER_SANITIZE_URL );
$this->setTitle( $title );
$this->setTemplate( $template);
}
function getUrl() {
return $this->url;
}
function getTemplate() {
return $this->template;
}
function getTitle() {
return $this->title;
}
function setTitle( $title ) {
$this->title = filter_var( $title, FILTER_SANITIZE_STRING );
return $this;
}
function setContent( $content ) {
$this->content = $content;
return $this;
}
function setTemplate( $template ) {
$this->template = $template;
return $this;
}
function asWpPost() {
if ( is_null( $this->wp_post ) ) {
$post = array(
'ID' => 0,
'post_title' => $this->title,
'post_name' => sanitize_title( $this->title ),
'post_content' => $this->content ? : '',
'post_excerpt' => '',
'post_parent' => 0,
'menu_order' => 0,
'post_type' => 'page',
'post_status' => 'publish',
'comment_status' => 'closed',
'ping_status' => 'closed',
'comment_count' => 0,
'post_password' => '',
'to_ping' => '',
'pinged' => '',
'guid' => home_url( $this->getUrl() ),
'post_date' => current_time( 'mysql' ),
'post_date_gmt' => current_time( 'mysql', 1 ),
'post_author' => is_user_logged_in() ? get_current_user_id() : 0,
'is_virtual' => TRUE,
'filter' => 'raw'
);
$this->wp_post = new \WP_Post( (object) $post );
}
return $this->wp_post;
}
}
<?php
namespace GM\VirtualPages;
/**
* @author Giuseppe Mazzapica <giuseppe.mazzapica@gmail.com>
* @license http://opensource.org/licenses/MIT MIT
*/
interface PageInterface {
function getUrl();
function getTemplate();
function getTitle();
function setTitle( $title );
function setContent( $content );
function setTemplate( $template );
/**
* Get a WP_Post build using viryual Page object
*
* @return \WP_Post
*/
function asWpPost();
}
<?php
namespace GM\VirtualPages;
/**
* @author Giuseppe Mazzapica <giuseppe.mazzapica@gmail.com>
* @license http://opensource.org/licenses/MIT MIT
*/
class TemplateLoader implements TemplateLoaderInterface {
public function init( PageInterface $page ) {
$this->templates = wp_parse_args(
array( 'page.php', 'index.php' ), (array) $page->getTemplate()
);
}
public function load() {
do_action( 'template_redirect' );
$template = locate_template( array_filter( $this->templates ) );
$filtered = apply_filters( 'template_include',
apply_filters( 'virtual_page_template', $template )
);
if ( empty( $filtered ) || file_exists( $filtered ) ) {
$template = $filtered;
}
if ( ! empty( $template ) &&file_exists( $template ) ) {
require_once $template;
}
}
}
<?php
namespace GM\VirtualPages;
/**
* @author Giuseppe Mazzapica <giuseppe.mazzapica@gmail.com>
* @license http://opensource.org/licenses/MIT MIT
*/
interface TemplateLoaderInterface {
/**
* Setup loader for a page objects
*
* @param \GM\VirtualPagesPageInterface $page matched virtual page
*/
public function init( PageInterface $page );
/**
* Trigger core and custom hooks to filter templates,
* then load the found template.
*/
public function load();
}
@gmazzap
Copy link
Author

gmazzap commented Sep 26, 2015

@nirajkvinit yes, "virtual_page_template" is the way to go, but withous seeing the code is not possble to say why it did not work.

@k00ni
Copy link

k00ni commented Oct 9, 2015

First, thanks for these helpful PHP code.

My local setup is:

  • Ubuntu, web root with WordPress is located under: /var/www/wordpress
  • PHP 5.4
  • no .htaccess in wordpress folder

I created a new plugin folder under wp-content/plugins and copied your stuff there, but calling

http://localhost/wordpress/custom/page

let me run in a 404 error. I found out, that i needed a .htaccess file active and running. So i created the following one:

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /wordpress/
    RewriteRule ^index\.php$ - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /wordpress/index.php [L]
</IfModule>

and placed it under /var/www/wordpress. After that, i could reach http://localhost/wordpress/custom/page.

If your path differs from mine, please adapt the following lines:

  • RewriteBase /wordpress/
  • RewriteRule . /wordpress/index.php [L]

and use your path. Notice: the path is relative to the root folder.

That configuration needs the mod_rewrite extension of Apache to be running. Otherwise it won't work.

@gmazzap
Copy link
Author

gmazzap commented Oct 9, 2015

@k00ni if you go in WordPress dashboard under Settings / Permalink page you find WordPress settings for permalink.

Setting there anything that is not "Default" WordPress will save the .htaccess for you with the proper path settings. And you don't need to create it manually.

Also consider, that if you use a different web server (e.g. Nginx) .htaccess is not of any help.

But, yes, this code requires "pretty permalink" feature enabled and the fastest way to enable it is to set WordPress permalink something different than "default" and set web server accordingly (if needed).

Codex has a page on the topic that list all the web server supported https://codex.wordpress.org/Using_Permalinks#mod_rewrite:_.22Pretty_Permalinks.22.

@nirajkvinit
Copy link

Thank you for replying @Giuseppe-Mazzapica. Your implementation used to load template part from theme. My intention was to load template part from my custom plugin. So, I extended your TemplateLoader and implemented my own which would load template from the plugin then fallback to your template loader if appropriate template not found. In-fact my virtual pages are being created dynamically if any url path comes after the root dynamic page in my logic. That way my plugin can handle the 404 of virtual page.

However, I had been facing another problem -

Say my virtualpage is /settings and when I try to access /settings/?custom_action=some_action I used to get 404 (NetworkError: 404 not found).

So, if I modify the code in function checkRequest () in class Controller from

$path = trim( $this->getPathInfo(), '/' );

to

$path = trim( parse_url( $this->getPathInfo(), PHP_URL_PATH ), '/');

then I can also access the get variables in the virtual page. If it works then perhaps you should update the code. :)

@nirajkvinit
Copy link

In wordpress version 4.4 I was getting undefined indexes for (name, year, monthnum, and day). I guess, something was changed in the function wp_old_slug_redirect in the query.php of wp-includes directory. I got rid of the notices by setting up these variables at the function setupQuery in the controller.php in $wp-query object.

@k00ni
Copy link

k00ni commented Apr 12, 2016

I used this code of @Giuseppe-Mazzapica and re-packaged it into a composer-package: https://github.com/plugins-first/fakepage, because i needed it to be available via Composer (use "plugins-first/fakepage": "*") and reusable from other plugins as well without the need to reimplement that functionality again and again. I am welcoming everybody to participate and add further features! :)

@enventa
Copy link

enventa commented Apr 23, 2016

Hi,
I have the need to create virtual pages which use the author.php template (archive or index, if it doesn't exist) of the current theme, whatever it might be, so the look of the page is the same as any other author page on the site. My issue is that the content I want to show is not a post, but a bunch of posts... just like a regular author/archive page does.

Using this plugin I can almost achieve what I need, but all the information (all posts) are shown as the content of one post, see the image attached below:

author

May be my question is: How can I create an author page of no-registered user (so virtual) hooking into the query results of that page? pre_get_posts hook doesn't help on this.

Could anyone assist on how to achieve what I need? Thank you very much!

@evronique
Copy link

evronique commented Aug 31, 2016

Hello!
Thanks for your code, it's very helpfull
In my case my first virtual page is a form and I need to pass argument with GET method to the second page. but I can't achieve that
I always have :
/custom/page and /custom/page/results/?myargs
how can I create virtual page with GET args? so that url will be /custom/page/results?args
Thanks for your help!

@tmairegasnighto
Copy link

@evronique, see nirajkvinit's comment above.

@rob-gordon
Copy link

Is it possible to use virtual pages, and have them routed correctly even when a second query variable is attached to the route?
E.G. http://mysite.com/myvirtualpage?diff_template=1

Right now, when I append ?diff_template=1 wordpress returns a 404.

@3pepe3
Copy link

3pepe3 commented Apr 13, 2018

Is there any way we can register the virtualpage on the menu editor (/wp-admin/nav-menus.php) ? Lest's say another accordion section with all the virtual pages that we have registered?

@selftrips
Copy link

What about feature image fo post|page?

@freewings89
Copy link

freewings89 commented Feb 1, 2019

I'm new to WP and i don't know how to implement and using the code. Can any body help me to figure it out. Thanks

@paulmiller3000
Copy link

A wonderful and insightful article you had written. I had tried to implement this in a sample plugin. When template files are in theme folder, it works great. However, I tried to set my own templates which are in my plugins. It doesn't work there. I was wondering whether you may provide a sample example or a snippet codes to do so?

Note: Yes! I had tried applying "virtual_page_template" filter. Perhaps, I am doing something wrong.

@nirajkvinit I realize it was several years ago now, but do you recall how you implemented custom page templates from inside the plugin itself? Trying to figure that out now.

Or @gmazzap, would you be willing to share? Thanks!

@gmazzap
Copy link
Author

gmazzap commented Aug 8, 2019

@paulmiller3000

The TemplateLoader class is specific for themes. That should be probably renamed ThemeTemplateLoader. However, there's the interface TemplateLoaderInterface so you can write another implementation that loads templates from the plugin folder and pass it to Controller.

@nirajkvinit
Copy link

A wonderful and insightful article you had written. I had tried to implement this in a sample plugin. When template files are in theme folder, it works great. However, I tried to set my own templates which are in my plugins. It doesn't work there. I was wondering whether you may provide a sample example or a snippet codes to do so?
Note: Yes! I had tried applying "virtual_page_template" filter. Perhaps, I am doing something wrong.

@nirajkvinit I realize it was several years ago now, but do you recall how you implemented custom page templates from inside the plugin itself? Trying to figure that out now.

Or @gmazzap, would you be willing to share? Thanks!

@paulmiller3000

That time I didn't know better, so I had overridden the load function of the class TemplateLoader with my own custom template loader - which used to load template files from a very specific location.

        public function load() {
		do_action( 'template_redirect' );		
		$template = $this->pdg_locate_views(array_filter($this->templates), TRUE);
	}

@paulmiller3000
Copy link

Thank you both! Still hacking away at this. Will post what I come up with if it's not too ugly!

@danielbenjamins
Copy link

danielbenjamins commented Nov 16, 2019

This is exactly what I was looking for and it's working great for me. I'm also using https://github.com/Rishita18/aap-task-1- for parsing JSON feeds and adding pagination to them, which is working great as well. Although I can't figure out a way to make both scripts work together, since I'm getting a 404 error once I click on any sub page (2, 3, etc.). When I use pagination on a real page, it's working perfectly.

@gmazzap Do you think this is possible?

@danielbenjamins
Copy link

danielbenjamins commented Nov 16, 2019

@paulmiller3000 @nirajkvinit Did you manage to get the custom template folder working? I was testing in a normal theme and it worked fine. Now I want to move it over to production, which is using a child theme, and now the template files can't be found.

@manav007
Copy link

@gmazzap, Thanks for the great plugin. However we are not able to access custom query through the URL
Have gave my 7 hours on the same thing. But no luck.
However when I create a Template page and assign it in the backend the query works fine.

I need to acheive the following
E.G. http://mysite.com/virtualpage?post_id=1

It goes to 404
Any help will be appreciated.

Thanks !

@paulmiller3000
Copy link

@paulmiller3000 @nirajkvinit Did you manage to get the custom template folder working? I was testing in a normal theme and it worked fine. Now I want to move it over to production, which is using a child theme, and now the template files can't be found.

@eaglejohn I built mine out in a plugin, not a theme. I'll post here in case it helps you or other visitors.

FYI, I'm using the WordPress Plugin Boilerplate. I added the following to the load_dependencies function in /includes/class-wp-stripe-connect-auto-provision.php:

/**
 * The namespace responsible for virtual pages         
 */
require_once WP_STRIPE_CONNECT_AUTO_PROVISION_PLUGIN_PATH . 'includes/wpscap-virtual-pages.php';

wpscap-virtual-pages.php is gmazzap's gm-virtual-pages.php file with the following addition at the bottom:

add_action( 'gm_virtual_pages', function( $controller ) {
    // Registration page 
    $controller->addPage( new \WPSCAP\VirtualPages\Page( '/registration' ) )
      ->setTitle( 'Registration' )      
      ->setTemplate( 'registration.php' );

    // Get Registrant page 
    $controller->addPage( new \WPSCAP\VirtualPages\Page( '/get-registrant' ) )
      ->setTitle( 'Registration' )
      ->setTemplate( 'get-registrant.php' );

    // Registration Received page 
    $controller->addPage( new \WPSCAP\VirtualPages\Page( '/registration-received' ) )
      ->setTitle( 'Registration Received' )
      ->setTemplate( 'registration-received.php' );

    // Registration Completed page 
    $controller->addPage( new \WPSCAP\VirtualPages\Page( '/registration-completed' ) )
      ->setTitle( 'Registration Completed' )
      ->setTemplate( 'registration-completed.php' );

} );

The above code is where I designated the names that will appear in the browser along with their corresponding templates, which are loaded below.

Next, I extended TemplateLoader.php as follows:

<?php 
namespace WPSCAP\VirtualPages;

class TemplateLoaderBSD extends TemplateLoader {
    public function wpscap_locate_template( $template_names, $load = false, $require_once = true ) {
        $located = '';

        foreach ( (array) $template_names as $template_name ) {            
            if ( ! $template_name ) {                
                continue;
            }
            if ( file_exists( WP_STRIPE_CONNECT_AUTO_PROVISION_PLUGIN_PATH . 'includes/templates/' . $template_name ) ) {                
                $located = WP_STRIPE_CONNECT_AUTO_PROVISION_PLUGIN_PATH . 'includes/templates/' . $template_name;                
                break;
            }
        }

        if ( $load && '' != $located ) {
            load_template( $located, $require_once );
        }

        return $located;
    }

	public function load() {
        // TO DO: Add support for Thesis theme: http://answers.diythemes.com/t/thesis-2-8-5-custom-page/1552

        do_action( 'template_redirect' );
        $template = $this->wpscap_locate_template(array_filter($this->templates), TRUE);

        $filtered = apply_filters( 'template_include',
          apply_filters( 'virtual_page_template', $template )
        );
        if ( empty( $filtered ) || file_exists( $filtered ) ) {
          $template = $filtered;
        }
        if ( ! empty( $template ) &&file_exists( $template ) ) {
          require_once $template;
        }        
	}
}
?>

That file checks to see if there is an actual template file. I created a templates folder under includes that contains those actual pages.

This approach might be a bit kludgy, but it worked for the four templates I needed. A future enhancement may be to create an admin interface for this.

@danielbenjamins
Copy link

@paulmiller3000 Thanks for the code! Turns out it was a plugin that was causing this problem (but not showing an error). After deactivating the plugin, all virtual pages started working again immediately...

@manav007
Copy link

manav007 commented Nov 20, 2019

@gmazzap, Thanks for the great plugin. However we are not able to access custom query through the URL
Have gave my 7 hours on the same thing. But no luck.
However when I create a Template page and assign it in the backend the query works fine.

I need to acheive the following
E.G. http://mysite.com/virtualpage?post_id=1

It goes to 404
Any help will be appreciated.

Thanks !

@eaglejohn Could you let me know, if this is possible ?

@gmazzap
Copy link
Author

gmazzap commented Nov 20, 2019

Hi everyone here. I see a lot going on, but don't really have the time to follow. The reason why I put this in a Gist instead of a proper repo, was to "release and forget".

Just to mention that you need something more complex/powerful/flexible you should probably look at https://github.com/Brain-WP/Cortex

@danielbenjamins
Copy link

I'll stick with your plugin Giuseppe, it works great for what I need. Cortex looks pretty complicated.

@bogal
Copy link

bogal commented Mar 10, 2020

Great plugin! Found it after looking for a more OO approach to WP plugins. I notice that it creates front-end pages - is it also possible to use this to create back-end / admin pages too?

@mzaheerdad
Copy link

Hi,
I a m facing problem on pagination permalinks. Let say i create a virtual page "members". In which i list all the members with pagination links.
The first page render successfully http://mysite/members. When i tried 2nd page http://mysite/members/2 it's leads to 404

@angel-rs
Copy link

angel-rs commented Jul 4, 2021

Hello, I'm using this gist for a plugin & I needed to allow passing query parameters, this gist as is doesn't support them (leads to 404).
Luckily it can be easily tweaked to bring support to query parameters.
Just need to tweak checkRequest in Controller.php
& updating the $path definition like so:

private function checkRequest() {
    $this->pages->rewind();
-   $path = trim( $this->getPathInfo(), '/' );
+   $path = trim(strtok($this->getPathInfo(), "?"), "/");
    while( $this->pages->valid() ) {
      if ( trim( $this->pages->current()->getUrl(), '/' ) === $path ) {
        $this->matched = $this->pages->current();
        return TRUE;
      }
      $this->pages->next();
    }
  }        

@brasofilo
Copy link

Bless your heart, @angel-rs , this was epic!
Thanks Giuseppe as well for such fine code 💯

-   $path = trim( $this->getPathInfo(), '/' );
+   $path = trim(strtok($this->getPathInfo(), "?"), "/");

@erinringland
Copy link

Works amazing! Thank you @gmazzap !

To others looking at this coming from StackOverFlow, the code on the gist works. Copying from here rather than the answer gets everything working properly.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment