Conceptually what I want to do is super simple. In my plugin, I want to add a single path/route to my wordpress site:
[mysiteurl]/testpath
… that loads a particular file, like:
[filepath-to-my-plugin]/testfile.html
I have played with wp-rewrite, flush_rules, add_filter(‘rewrite_rules_array’, xxx), but all I got was for the site to accept the path but display the home page.
Clearly I’m missing something really simple, but I’ve googled for a while without finding what I need. Any ideas?
1 Answer
The idea is just to programmatically create a path/url in a plugin for a WordPress site (like, “[mysite]/mypath”), and then load an arbitrary html or php file. In case anyone else is looking for something similar, this works for me (in my main plugin function file):
register_activation_hook(__FILE__, 'myplugin_activate');
function myplugin_activate () {
create_custom_page('mytestpath');
}
function create_custom_page($page_name) {
$pageExists = false;
$pages = get_pages();
foreach ($pages as $page) {
if ($page->post_name == $page_name) {
$pageExists = true;
break;
}
}
if (!$pageExists) {
wp_insert_post ([
'post_type' =>'page',
'post_name' => $page_name,
'post_status' => 'publish',
]);
}
}
// End Plugin Activation
//Start Catching URL
add_filter( 'page_template', 'catch_mypath' );
function catch_mypath( $page_template ) {
if ( is_page( 'mytestpath' ) ) {
$page_template = __DIR__.'/mypage.html';
}
return $page_template;
}
References:
- This answer about creating custom pages in a plugin. Thanks fuxia.