Can I add “virtual” page in WordPress?

2019-08-15 19:31发布

问题:

On my WordPress site, I would like to create "virtual" page. By virtual page I mean the content that I can link to by URL. I'm using Facebook Webhooks and I would like to have a callback URL like this: https://example.com/facebook-webhook. I'd like it to be done via plugin, without actually adding any page to the database. Is there any way to add a page in WordPress that way?

For now I'm using https://example.com/?facebook-webhook and checking for isset( $_GET['facebook-webhook'] ) in the init action. I would love to have it without the ? though.

回答1:

You can do this using a rewrite and query vars to use your custom php file as a template:

//1. define a path for later
define('PLUG_PATH', WP_PLUGIN_DIR . '/' . basename(dirname(__FILE__)));



//2. add a wp query variable to redirect to
add_action('query_vars','plugin_set_query_var');
function plugin_set_query_var($vars) {
    array_push($vars, 'is_new_page'); // ref url redirected to in add rewrite rule

    return $vars;
}


//3. Create a redirect
add_action('init', 'plugin_add_rewrite_rule');
function plugin_add_rewrite_rule(){
    add_rewrite_rule('^mynewpage$','index.php?is_new_page=1','top');

    //flush the rewrite rules, should be in a plugin activation hook, i.e only run once...

    flush_rewrite_rules();  
}

//4.return the file we want...
add_filter('template_include', 'plugin_include_template');
function plugin_include_template($template){


    // see above 2 functions..
    if(get_query_var('is_new_page')){
        //path to your template file
        $new_template = PLUG_PATH.'/template.php';
        if(file_exists($new_template)){
            $template = $new_template;
        } 
        // else needed? up to you maybe 404?
    }    

    return $template;    

}