WordPress How To Get Variable from Rewrite Rules

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.

The Correct Way To get Get Variable from Rewrite Rules

But some conditions must be fulfilled. Please read on.

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.

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.

The Full Code

Make sure you press save at Settings -> Permalinks.