In WordPress how do I pass multiple variables into the URL and retrieve them?

For some reason I can only retriever the first variable, in this instance, “product_category” out of the URL http://localhost/coffeesite/?product_category=coffee&brand=bourbon .

I’m outputting javascript to confirm that I’ve set the variable, but again, only coffee will be alerted, and not brand. I’m using WordPress’s ‘get_query_var’. See code below:

Read More
<?php 
        echo '<script> product_category = "' . get_query_var('product_category') . '"; 
                       brand = "' . get_query_var('brand') . '";
                       alert(product_category);
                       alert(brand);
             </script>'; 
?>

Any help would be appreciated – I’m struggling to solve it!

Related posts

1 comment

  1. Since you are testing, maybe you could test the php directly? The function get_query_var is just a wrapper for the generic php array $_GET. You should have these values available at $_GET[‘product_category’] and $_GET[‘brand’]. But instead of assuming everything is where it is supposed to be, why not check what you actually have?

    <?php 
        add_settings_error("var-test", "var-test", implode(", ", array_keys($_GET)));
    ?>
    

    Disclaimer: I am a Drupal developer, not WordPress, but they are both php.
    I am using the documented message tool here, for a little cleaner php code.
    https://codex.wordpress.org/Function_Reference/add_settings_error
    You could still use your javascript if you would like:

    <?php 
        echo '<script> alert( '. implode(", ", array_keys($_GET)) .');
             </script>'; 
    ?>
    

    Second possibility. The reason for using a wrapper function instead of the raw core is for what it provides in that wrap. My normal assumption is sanitation and security filters, which are poor for testing but essential for production environments. However, with a little bit of reading on the function you are using, it says it only returns values for known query objects and if you are using custom variables in the url you should register them. https://codex.wordpress.org/Function_Reference/get_query_var
    Have you registered “brand”?

Comments are closed.