0

I have a Wordpress site I'm developing, which needs to pass parameters in the URL. I've got to the point where www.example.com/stats/?stat-name works - it takes me to my stats-pages.php template, where I can process it.

What I need to do is to clean up the URL so that the ? is removed, and the URL becomes www.example.com/stats/stat-name instead of www.example.com/stats/stats/?stat-name

In my functions.php, I have:

function add_query_vars($aVars) {
    $aVars[] = "stats";
    return $aVars;
}

// hook add_query_vars function into query_vars
add_filter('query_vars', 'add_query_vars');

In my .htaccess, I have

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule  ^stats/^([A-Za-z0-9]+)/$ /stats=$1 [QSA,L]
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

Can anyone help please? Thanks!

  • I should add that param-pages.php is the template used by a page in WP called 'Param' – willothewisp May 27 '20 at 09:06
  • What code have you written already? Please have a read of [this guide on producing code for a good quality question](https://stackoverflow.com/help/minimal-reproducible-example), then include and mark up your code in your question. Cheers! – Joundill May 27 '20 at 09:08
  • 2
    The proper way to do this would be not to try and hack this into the .htaccess yourself, but use the functionality WP provides for stuff like this. https://codex.wordpress.org/Rewrite_API/add_rewrite_rule – CBroe May 27 '20 at 09:39
  • Have a look at https://stackoverflow.com/questions/32447359/wordpress-convert-url-query-string-to-static – Unbranded Manchester May 27 '20 at 10:03
  • THANK YOU @CBroe, I worked out a solution from your link. – willothewisp May 27 '20 at 10:15

1 Answers1

1

The solution was as follows:

Referencing https://codex.wordpress.org/Rewrite_API/add_rewrite_rule for the example.

In functions.php:

function custom_rewrite_tag() {
  add_rewrite_tag('%stats%', '([^&]+)');
}
add_action('init', 'custom_rewrite_tag', 10, 0);

function custom_rewrite_rule() {
    add_rewrite_rule('^stats/([^/]*)/?','index.php?page_id=1385&stats=$matches[1]','top');
  }
add_action('init', 'custom_rewrite_rule', 10, 0);

In stats-pages.php, you can then do:

/**
 * Template Name: Stats
*/
get_header(); 

global $wp_query;
echo 'Stats : ' . $wp_query->query_vars['stats'];

get_footer(); 

I removed my RewriteRule from .htaccess, as it was no longer needed.

IMPORTANT: You MUST flush and regenerate the rewrite rules within Wordpress (Settings -> Permalinks -> Save Changes) in order for the new URLs to work.

An URL such as https://example.com/stats/btts/ will then work and pass the stats parameter to the page.