0

I have created a small function to rewrite a get variable. First, I created the page 'download', and I want a get variable to be used for the file attribute. This is an working URL: http://example.com/download/?file=file

But when I use add_rewrite_rule to make the url look like this: http://example.com/download/file, It doesn't work.

The function:

function createRewriteRules() {
    add_rewrite_rule('download/([^/]*)', 'index.php/download/?file=$matches[1]', 'top');
}
add_action('init', 'createRewriteRules');

I have also tried the following:

function createRewriteRules() {
    add_rewrite_rule('download/([^/]*)', 'download/?file=$matches[1]', 'top');
}
add_action('init', 'createRewriteRules');

On both, $wp_query returns "file" as pagename instead of "download".

Updated:

function createRewriteRules() {
    add_rewrite_tag('%file%', '([^&]+)');
    add_rewrite_rule('download/([^/]+)/?$', 'index.php/?pagename=download&file=$matches[1]', 'top');
}

And a reflush doesn't work eighter, while index.php/?pagename=download&file=file does work. The rewrite rule also got added to the .htaccess file.

2

Your rerite rule is incorrect. It should be (assuming download is name or slug of the page):

add_rewrite_rule('^download/([^/]+)/?$', 'index.php?pagename=download&file=$matches[1]', 'top');

Also, you need to declare the file query var. A sample and working code:

function createRewriteRules() {
    add_rewrite_tag('%file%', '([^&]+)');
    add_rewrite_rule('^download/([^/]+)/?$', 'index.php?pagename=download&file=$matches[1]', 'top');
}
add_action('init', 'createRewriteRules');

Note: Don't forget to flush rewrite rules after adding new rewrite rules.

  • Doesn't work... I've added the results to my original question. – Jeroen Nov 11 '15 at 12:31
  • Strange, I tested de code before posting and tested again and it is working. That extra / after index.php is really irrelevant in most servers and makes no difference. It is also not correct from a strict syntax perspective. I'm really curious and I would like to know how it can be working with it while not working without it. To be homest, I think you have not tested properly this code. – cybmeta Nov 11 '15 at 17:59
  • 1
    I found that the problem didn't had anything to do with the add_rewrite_rule tag. There was another .htaccess file in the root folder of the server (where I didn't had access to) which caused some problems. I'll mark your answer as the correct one as normally, that would have fixed it. – Jeroen Nov 13 '15 at 12:48

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.