2

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?

2

1 Answer 1

3

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:

1
  • Am I wrong, or could the admin delete the page that was added during plugin activation? Would there be a method of doing this that would not leave a vulnerable page behind? Mar 3, 2018 at 19:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.