Making a plugin file accessible via url rewrite?

Mark,

I hate to say it, but you’re going about this the wrong way. PHP files in your plug-in should never be accessed directly in this way. Instead, they should be loaded from within WordPress just like everything else.

Here are some alternative paths you could take:

Create an admin page that displays your stats

This is a page accessible from within WordPress by authenticated users only. If you use the correct API, this page will look very clean and will display your simple stats however you want. Since it’s inside WordPress to begin with, you’ll already have access to the entire WP API without needing to load wp-blog-header.php directly.

Use your existing system, but register the rewrite with WordPress

You should never modify your .htaccess file directly. This file can be changed when you add new plug-ins or change your permalink structure, meaning you’ll lose your customizations. Instead, you can create a custom rewrite by making a function call within WordPress itself:

add_action( 'init', 'my_rewrite' );
function my_rewrite() {
    global $wp_rewrite;

    add_rewrite_rule('list-data/$', WP_PLUGIN_URL . '/data-fetcher/list-data.php', 'top');
    $wp_rewrite->flush_rules(true);  // This should really be done in a plugin activation
}

This will add your custom rule to the top of the WordPress rewrite rules and should skip any other redirects WordPress matches against the regex.

For a great example of how you can implement this kind of simple rewriting in a plug-in, check out Ozh’s tutorial on redirecting a pretty login URL:

Leave a Comment