I used add_rewrite_rule to redirect a nice URL to the right page.
This is the rule:
add_rewrite_rule('^([^/]*)/([^/]*)/([^/]*)/([^/]*)/([^/]*)/?','index.php?pagename=auto&id=1234', 'top' );
So if I go to the following URL: website.com/cars/brand/model/car/1234 It wil go to the page with pagename auto.
On this page is a shortcode that needs to get this id. If I echo $_GET[‘pagename’] it prints ‘auto’. But if I print $_GET[‘id’] it contains nothing. Why can’t I get that value in the shortcode??
This rule works fine:
add_rewrite_rule('^([^/]*)/([^/]*)/([^/]*)/([^/]*)/([^/]*)/?','index.php?pagename=auto&id=' . $_GET['id'], 'top' );
But I want something like this:
add_rewrite_rule('^([^/]*)/([^/]*)/([^/]*)/([^/]*)/([^/]*)/?','index.php?pagename=auto&id=$matches[5]', 'top' );
I don’t know why the $matches is empty.
Complete code:
function redirectUrls() {
flush_rewrite_rules();
add_rewrite_rule('^([^/]*)/([^/]*)/([^/]*)/([^/]*)/([^/]*)/?','index.php?pagename=auto&id=1234', 'top' );
}
add_action('init', 'redirectUrls');
I put this code in my plugin
EDIT (ANSWER)
Oke I’ve used this tutorial and it works: http://www.janes.co.za/wordpress-permalinks-and-custom-_get-variables/
I also used the answer of @Sacroma
function add_query_vars($aVars) {
$aVars[] = "id"; // represents the name of the product category as shown in the URL
return $aVars;
}
add_filter('query_vars', 'add_query_vars');
function add_rewrite_rules($aRules) {
$aNewRules = array('^([^/]*)/([^/]*)/([^/]*)/([^/]*)/([^/]*)/?$' => 'index.php?pagename=auto&id=$matches[5]');
$aRules = $aNewRules + $aRules;
return $aRules;
}
add_filter('rewrite_rules_array', 'add_rewrite_rules');
Now I can use the get_query_var(“id”)
I think you are looking for
get_query_var("id")
it retrieves the GET parameter from a pretty url.See the codex for more details.
https://codex.wordpress.org/Function_Reference/get_query_var