Last Updated: July 07, 2022
·
17.8K
· bainternet

Create WordPress virtual page "On The Fly"

Here is a little class i cooked up to create a fake/virtual page "On the Fly" in WordPress:

<?php
if (!class_exists('WP_EX_PAGE_ON_THE_FLY')){
    /**
    * WP_EX_PAGE_ON_THE_FLY
    * @author Ohad Raz
    * @since 0.1
    * Class to create pages "On the FLY"
    * Usage: 
    *   $args = array(
    *       'slug' => 'fake_slug',
    *       'post_title' => 'Fake Page Title',
    *       'post content' => 'This is the fake page content'
    *   );
    *   new WP_EX_PAGE_ON_THE_FLY($args);
    */
    class WP_EX_PAGE_ON_THE_FLY
    {

        public $slug ='';
        public $args = array();
        /**
         * __construct
         * @param array $arg post to create on the fly
         * @author Ohad Raz 
         * 
         */
        function __construct($arg){
            add_filter('the_posts',array($this,'fly_page'));
            $this->args = $args;
            $this->slug = $args['slug'];
        }

        /**
         * fly_page 
         * the Money function that catches the request and returns the page as if it was retrieved from the database
         * @param  array $posts 
         * @return array 
         * @author Ohad Raz
         */
        public function fly_page($posts){
            global $wp,$wp_query;
            $page_slug = $this->slug;

            //check if user is requesting our fake page
            if(count($posts) == 0 && (strtolower($wp->request) == $page_slug || $wp->query_vars['page_id'] == $page_slug)){

                //create a fake post
                $post = new stdClass;
                $post->post_author = 1;
                $post->post_name = $page_slug;
                $post->guid = get_bloginfo('wpurl' . '/' . $page_slug);
                $post->post_title = 'page title';
                //put your custom content here
                $post->post_content = "Fake Content";
                //just needs to be a number - negatives are fine
                $post->ID = -42;
                $post->post_status = 'static';
                $post->comment_status = 'closed';
                $post->ping_status = 'closed';
                $post->comment_count = 0;
                //dates may need to be overwritten if you have a "recent posts" widget or similar - set to whatever you want
                $post->post_date = current_time('mysql');
                $post->post_date_gmt = current_time('mysql',1);

                $post = (object) array_merge((array) $post, (array) $this->args);
                $posts = NULL;
                $posts[] = $post;

                $wp_query->is_page = true;
                $wp_query->is_singular = true;
                $wp_query->is_home = false;
                $wp_query->is_archive = false;
                $wp_query->is_category = false;
                unset($wp_query->query["error"]);
                $wp_query->query_vars["error"]="";
                $wp_query->is_404 = false;
            }

            return $posts;
        }
    }//end class
}//end if

Usage:

<?php
$args = array(
        'slug' => 'fake_slug',
        'post_title' => 'Fake Page Title',
        'post content' => 'This is the fake page content'
);
new WP_EX_PAGE_ON_THE_FLY($args);

you can overwrite any of the post object fields in the $arg array.

Enjoy :)

12 Responses
Add your response

You can use it for many things such as creating a custom API endpoint in WordPress,
Split content across multiple urls like what we have on WordPress.org’s plugin directory (description,install,faq,...)
and i use it mostly for creating "sub posts" for custom post types

over 1 year ago ·

Hey bainternet --- this code is AWESOME!

Don't let the jerk above talk to you about being rude. I have a Wordpress website that needed "content pages" built on the fly as a user click a link within an existing page. Your code worked like a charm.

Usage: I put your Class and Args code in my theme's functions. php. The Args code went inside a separate function like this:
makevirtual() {
$args = array( 'slug' => 'fake
slug', 'posttitle' => 'Fake Page Title', 'post content' => 'This is the fake page content' );
new WP
EXPAGEONTHEFLY($args);
}
Changed the fake_slug parameter to a slug name that matched up with a existing content page and away it went.

I use a little javascript code to call the function: onclick="<?php make_virtual(); ?>.

What is also beautiful about this is that inside the make_virtual($parameter1, $parameter2) function I can pass whatever variables I need to. LOL

EXCEPT one thing.. these aren't FAKE pages for me.. they are REAL and useful and added to my database for viewing by all.

Cheers,
Bob Campbell
newscruzin.com

over 1 year ago ·

Good day!

Do you have a demo for this code? and also where will I put the code to call the class? I did try to test the code but it display 404 error :(

url:
http://localhost/wp/proj/1

I want it to display the project 1 without creating any page/post. Just the main proj page will hold the links for the virtual pages.

over 1 year ago ·

Firstly let me say that I am a total rookie at all of this WP stuff. However, I googled my idea of creating WP pages on the fly and you came up. Not sure that this will work for me, but I'll try to explain as best I can. I have menu items at widstrand.com some of which link to my content, some to other sites, specifically http://widstrand.com/galleries/wine/ go to pulldown "wine". I would like these links to be displayed in branded Widstrand pages from my site, but would rather not insert them in a page. Will your code do this? Thanks, Russ

over 1 year ago ·

What I like doing (when I have a bunch of these, aka frontend profiles with a bunch of subpages). Add the rewrites for each page + query_vars, pre_get_posts to set posts_per_page to 1 (otherwise index.php pulls 10), template_include to pull in page.php, the_content filter to pull in a custom .php page, the_title filter to do the same.

Remember in the filters and the pre_get_posts to check for the query_var, in_the_loop(), and !is_nav_menu_item

over 1 year ago ·

Can I used this to dynamically create pages that are listed under categories? I am trying to use this to create around 200 hundred small pages that will be listed under various categories and subcategories on my blog e.g.
http://onemonthspanish.com/learn-spanish/vocabulary/ (category)

http://onemonthspanish.com/learn-spanish/vocabulary/days-of-the-week/ (subcategory)
http://onemonthspanish.com/vocabulary/days-of-the-week/friday (post).

Should I include the entire path including category/subcategory as part of the fake_slug? e.g. 'slug' => 'vocabulary/days-of-the-week/friday'?

over 1 year ago ·

You almost made my day. Any way to add some script enqueuing?

over 1 year ago ·

Excellent! Just what I need to build API endpoints. But how can I set the template? For normal pages, the template is stored in post_meta, but I can't see how you can have post meta data for a virtual page since it's ID is fake

over 1 year ago ·

what is about feature image for post?

over 1 year ago ·

I signed up on this site just to congratulate the script author. Just what I was looking for! And with a little tweaking, works very well for my purpose.

Newscruzer said he added the class directly into the functions.php. I chose to save the class as its own file in the theme root. Add:

requireonce("onthe_fly.class.php");
makevirtual();

...in your functions.php, just before calling the function that invokes the class. This way if you ever change themes you don't have to do too much re-write in the functions.php file. Customize newscruzer's makevirtual() function to your own needs. You can parse url segments or GET variables for some really powerful applications.

over 1 year ago ·

Thanks. It works great. Just missing the "s" of $args in "function __construct($arg)".

over 1 year ago ·

I added it to an include to my functions.php. As far as usage.. should I call that class from within functions also to generate the fake page?

over 1 year ago ·