willothewisp
willothewisp

Reputation: 53

Cleaning up URLs with parameters in Wordpress

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!

Upvotes: 0

Views: 1349

Answers (1)

willothewisp
willothewisp

Reputation: 53

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.

Upvotes: 1

Related Questions