PHP Version 5+
The first thing to do for the first 2 methods I will describe below, is to create the page in Wordpress. Select Pages-> New to create it, with title "my-page" or "My Page". The slug should be "my-page" in both cases, unless already exists. Don't use "my_page".
There are several ways to manage front-end pages within a plugin.
The one I like the most is to have the page in the plugin's directory and then copy it to the theme's directory, as shown in the following example.
Create the form as you would do normally and save it at your plugin's directory.
This file will be the template for the page in the stylesheet directory. The page must be located in this directory, as far as I know, for WP to load it.
Example:
// Make sure you define in your plugin's main script the location of the plugin, with a code like this:
// Holds the absolute path to MyPlugin directory, without slashes.
if ( !defined( 'MyPlugin_DIR' ) ) define( 'MyPlugin_DIR', __DIR__ );
function CopyFile() {
$TemplateFileSourceURL = MyPlugin_DIR . '/my-page.php'; // Address to your file in the plugin directory
$TemplateFileTargetURL = get_stylesheet_directory() . '/page-my-page.php'; // Note the "page-" prefix, it is necessary for WP to select this file instead of the general "page.php". The name after the prefix must match the slug of the page created in WP.
if ( !file_exists( $TemplateFileSourceURL ) ) {
return FALSE;
}
$GetTemplate = file_get_contents( $TemplateFileSourceURL );
if ( !$GetTemplate ) {
return FALSE;
}
$WriteTemplate = file_put_contents( $TemplateFileTargetURL, $GetTemplate );
if ( !$WriteTemplate ) {
return FALSE;
}
return TRUE;
}
The other method involves creating the page and saving it in the theme's directory as a template file or just as a page.
To make it a template, you have to add in the first line the following comment:
/*
Template Name: MyPage
*/
MyPage can be any name. Then go to the page editor in WP and select the MyPage template in the right bar. It should be there when you reload the editor's page.
You don't have to make it a template if you add the prefix "page-" to the name of the file in the theme's directory. i.e. page-my-page.php.
The last method is to create the file, save it wherever you want and load WP with a code like this in the first lines:
NOTE: No need to create the page in WP if this method is used, it will do nothing, although you might have to redeclare user's variables and functions.
require_once ('WPBlogUrl/wp-load.php'); // Make sure WPBlogUrl points to the blog's url.
Which method is the best one? Depends on your requirements, but if you don't want to have to add manually the front-end pages in the theme's directory, I think the first option is the best one.
Don't forget to delete the file in the uninstall script when the plugin is deleted.
Hope this helps.
Felipe Alameda A.