0

I have a custom template file called page_system.php. I have a page in Wordpress called "System" which uses this template. The path to view this page is:

www.mysite.com/system/

I want a way via htacess or otherwise, that would allow me to add anything after the path and put it in a get variable, so that I can use the variable as I see fit. I want it to ignore the built in Wordpress paths after the last '/'.

So, for example,

www.mysite.com/system/variable1/variable2 

would look the same in the URL bar, but it would actually show

www.mysite.com/system/?getvariables=variable1/variable2

My attempts at editing the .htaccess file so far haven't worked. My most recent failed attempt is:

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /

RewriteRule ^\/system\/(.*)$ system/?getvariables=$1 [QSA,L]

RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress

If anybody could help I would be very grateful!

1

You need to add a rewrite rule to WordPress. There are several options to do it depending on your exact needs.

Maybe the most general is using add_rewrite_tag() and add_rewrite_rule():

add_action( 'init', 'cyb_rewrite_rules' );
function cyb_rewrite_rules() {
    add_rewrite_tag( '%variable1%', '([^&]+)' );
    add_rewrite_tag( '%variable2%', '([^&]+)' );
    add_rewrite_rule( ^system/([^/]*)/([^/]*)/?', 'index.php?pagename=$matches[1]&variable1=$matches[2]&variable2=$matches[3]', 'top' );
}

Now, if the URL match the regext "system/([^/])/([^/])/", for example this one:

https://example.com/system/value1/value2

The page "system" will be queried by WordPress and you will be able to get the extra values using get_query_var():

$variable1 = get_query_var( 'variable1' );
$variable2 = get_query_var( 'variable2' );

Both functions, add_rewrite_tag() and add_rewrite_rule(), are wrappers of WP_Rewrite methods.

Note: after a new rewrite rule is added to WordPress, the set of rules need to be flushed and rebuild. This can be done with flush_rewrite_rules() function. This function makes a database operation that it's needed only once, that is why it is commonly used in plugin activation/deactivation hooks:

register_deactivation_hook( __FILE__, 'flush_rewrite_rules' );
register_activation_hook( __FILE__, 'cyb_activation_hook' );
function cyb_activation_hook() {
    flush_rewrite_rules();
}

Rewrite rules can be flushed also in "Settings -> Permalinks"; just click "Save" button and rewrite are rebuilt.

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.