0

I'm having some issue rewriting a page URL with wordpress. I tried with regular apache mod_rewrite, but the result was inconclusive. So I chose to focus on wordpress rewriting

my dev domain is:

http://localhost/randomwebsite/

I'm trying to rewrite this adress

/index.php?p=13806&annee=2014

as

/resultats/2014/

where resultats is p=13806 and 2014 is 'annee' (year in french)

my functions.php:

function add_result_url() {
    add_rewrite_rule('^resultats/([0-9]+)/?', 'index.php?p=13806&annee=$matches[1]', 'top');
    add_rewrite_tag('%annee%','([0-9]+)');
};
add_action('init', 'add_result_url');
flush_rewrite_rules();

my template file

global $wp_query;
$season = $wp_query->query_vars['annee'];
var_dump ($wp_query->query_vars['annee']);

the var_dump return a null on

/resultats/2014/

but works on

resultats/?annee=2014

/index.php?p=13806&annee=2014 (wich redirect on the first one)

Thanks for your help

EDIT 1

I check the 2 link from ihor's answear but couldn't get it worked with:

  functions.php 
function add_custom_query_var( $vars ){
        $vars[] = "annee";
        return $vars;
    }
    add_filter( 'query_vars', 'add_custom_query_var' );
    function add_rewrite_rules($aRules) {
        //add_rewrite_rule('^resultats/([^/]*)/([^/]*)/$', '?p=13806&annee=$matches[1]&gp=$matches[2]', 'bottom');
        $aNewRules = array('^resultats/([0-9]*)/$' => 'index.php?p=13806&annee=$matches[1]');
        $aRules = $aNewRules + $aRules;
        return $aRules;
    }
    add_filter('rewrite_rules_array', 'add_rewrite_rules');

and

template file:
if(isset($wp_query->query_vars['annee'])) {
$season = urldecode($wp_query->query_vars['annee']);
}
var_dump ($season);
var_dump ($_GET["annee"]);
Kable
  • 31
  • 3

1 Answers1

0
  1. You don't need to add rewrite_tag because you are actually catching this var in $matches[1].
  2. Are you sure WordPress knows this var called annee? Maybe you need to register this var first.

See these two SO questions for detailed explanations:

How to pass extra variables in URL with Wordpress

Passing and retrieving query vars in wordpress

Community
  • 1
  • 1
Ihor Vorotnov
  • 1,678
  • 1
  • 13
  • 22
  • Edited my question, but still stucked – Kable Mar 20 '15 at 15:24
  • first of all, install and use 2 plugins for debugging - Query Monitor and Rewrite Rules Inspector. The first one will show you everything what's going on under the hood - how WP parses the request, which variables it picks up etc. The second one will allow you to test your rewrite rules and see if there's another rule which is intercepting the request. The catch with rewrite rules is in their order - WP uses the first matched one and ignore the rest. From your question it's hard to understand where the problem lies. The whole rewrite topic is a bit tricky and needs some debugging. – Ihor Vorotnov Mar 20 '15 at 16:37