fwea7g
Last Updated: November 22, 2017
·
7.697K
· bainternet
1cdd42c841a307d7460954942e71877e

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 :)

Say Thanks
Respond

9 Responses
Add your response

2307
1900150 10203074354438338 1015529188 n

Excuse me, I don't mean to be rude but how is this really useful?

over 1 year ago ·
2327
1cdd42c841a307d7460954942e71877e

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 ·
9523

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 ·
9901
25628c838da855845cda104ee738463c

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 ·
11276
0 wfmgo2ohcrifdchhiwdgomdoczjiwchhiasgomi9hrdrn6c8ldwakax4jumqh532e2upadjntaoi

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 ·
15099
Em g2gh6 normal

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 ·
15724
0 hc1ylyaltfz4q1wqctl3l0a8y7rrq1uqc5f3l0shtdxiibunukitwxjakckxbqs43ta8ozx0sxu9

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 ·
29397

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

28 days ago ·
29454

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

7 days ago ·