Codementor Events

Creating a WordPress Rewrite Rule that points to a file on the server and sends variables

Published Jul 19, 2019Last updated Jan 25, 2024
Creating a WordPress Rewrite Rule that points to a file on the server and sends variables

Have you ever tried to rewrite a WordPress URL to make it point to a file on the server?

I initially tried doing this:

// Add Custom Rewrite Rules
function custom_rewrite_basic() {
  flush_rewrite_rules();
  add_rewrite_rule('^leaf/([0-9]+)/?', 'wp-content/plugins/my-plugin/index.php?leaf=$matches[1]', 'top');
}
add_action('init', 'custom_rewrite_basic');

but I had to find out that WordPress doesn't support adding a rewrite rule that doesn't point to index.php

Hence I went for the .htaccess method:

RewriteRule ^index\.php$ - [L]
RewriteRule ^leaf/([0-9]+)/? /wp-content/plugins/my-plugin/index.php?leaf=$1 [QSA,L]

but this wasn't working the way I was expecting it to. It just wasn't redirecting to my file. Come to think about it now, I don't remember if I inserted it at the top of the .htaccess file so it could be read first, but in case you try it, don't forget to put it at the top.

Finally, I went for the parse_request hook, which proved to be a great way to do it.
I inserted this snippet inside my child theme and everything worked out:

add_action( 'parse_request', function( $wp ){
  // The regex can be changed depending on your needs
  if ( preg_match( '#^leaf/(.*)/?#', $wp->request, $matches ) ) {
    // Get the Leaf Number
    $leaf = $matches[1]; 

    // Define it for my-plugin's index.php
    $_GET['leaf'] = urldecode($leaf);

    // Load your file - make sure the path is correct.
    include_once WP_CONTENT_DIR . '/plugins/my-plugin/index.php';
    exit; // and exit
  }
});

Note that in order to be safe when collecting and processing the GET variable, you might need to apply some cleaning to it. Example: mysql_real_escape_string, htmlspecialchars, strip_tags, stripslashes, preg_quote, escapeshellarg, escapeshellcmd, etc.

Discover and read more posts from Theo
get started
post commentsBe the first to share your opinion
Matthew Kennedy
3 months ago

Been struggling with this for a couple of hours now and this code worked perfect. Just a note to anyone else using it, you do need to keep the hash symbols #. Thanks Theo

Show more replies