I have added a query variable with the following function:

function add_my_query_var() {
    global $wp;
add_filter('init', 'add_my_query_var');

Now on a specific page (author)example.com/author/admin/myvar1, $wp_query returns:

WP_Query Object
    [query] => Array
            [author_name] => admin
            [myvar1] => 

    [query_vars] => Array

So I can see that the variable is set. However since it is empty, I cannot use following condition to check:

if ( get_query_var('myvar1') ) {
    echo "is set";

What is other way to check if the myvar1 exists or not? I cannot use $_GET because of permalinks.

Edit: Here's the code to rewrite the URL:

add_rewrite_rule('author/([^/]+)/myvar1/?$', 'index.php?author_name=$matches[1]&myvar1=$matches[2]', 'top');
  • What are you trying to achieve? How are you passing "myvar"? Are you passing it via a rewrite structure? If so, what is that rewrite structure? – engelen Jun 25 '14 at 8:18
  • I want to create a custom url on author profile, eg. /author/myvar1 and on the profile page I want to check if there is myvar1 in the url, then display posts using a different query. I have added rewrite rule and everything works fine. now I only want to check if there is myvar1 in the URL or not. I could use $_GET but that would not work because of permalink. Hope it makes sense. – jay Jun 25 '14 at 8:27
  • This isn't very easy to achieve, as WordPress uses a default value for all query vars. Could you post your rewrite structure here? When myvar1 is filled, e.g. in example.com/author/jay/somevar, does get_query_var( 'myvar1' ) return that value (in this case, "somevar")? – engelen Jun 25 '14 at 8:32
  • added code in the question. – jay Jun 25 '14 at 8:39
  • Please answer the second question in my last comment. – engelen Jun 25 '14 at 8:48

You should probably provide different default if empty string is indistinguishable from your value.

$myvar = get_query_var( 'myvar1', false );

if ( false !== $myvar ) {

    // stuff

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.