I was scratching my head on how to get the variable from WordPress rewrite rules. In one of Stackoverflow post, it was mentioned we could use $_GET and in some posts proposed to use get_query_var() but when I tried both were emptied.
|
1 2 3 |
echo 'my var '.$_GET['myvariablename']; //return empty value |
The Correct Way To get Get Variable from Rewrite Rules
But some conditions must be fulfilled. Please read on.
|
1 |
get_query_var('myvariablename'); |
If Using get_query_var is still Empty means you use non standard variable name
Here is the list of standard query vars that you can use.
Register Your Variable Name
If you use your custom variable, you must add the variable as below.
|
1 2 |
add_filter( 'query_vars', function add_query_vars($qvars){ $qvars[] = "myvariablename";} ); |
Ensure Your Regex Has ^ at the beginning and $ at the end
If not, WordPress standard rewrite rules will be executed first and you can ‘t get your variable value.
|
1 2 3 |
add_rewrite_rule('^jemputan-kahwin/([-a-z0-9]+)/?$', 'index.php?pagename=jemputan-kahwin&advertiser_slug=$matches[1]', 'top'); |
The Full Code
Make sure you press save at Settings -> Permalinks.
|
1 2 3 4 5 6 7 8 9 10 |
function add_rewrite_rules(){ add_rewrite_rule('^jemputan-kahwin/([-a-z0-9]+)/?$', 'index.php?pagename=jemputan-kahwin&advertiser_slug=$matches[1]', 'top'); } add_action( 'init', 'add_rewrite_rules'), 0 ); add_filter( 'query_vars', function add_query_vars($qvars){ $qvars[] = "myvariablename";} ); |