phpwordpresswidgetadd-filtergetparameter

Wordpress add_filter('query_vars', 'my_new_vars'); not working as expected


I have an issue with Wordpress (there's a shocker), where it removes my get parameter, which i understand thats a WP feature for security and some other reasons.

What i'm trying to achieve is the following:

  1. Load product page
  2. When customer clicks book now they are redirected to an enquire now form
  3. On enquire now form there is widget that retrieves what product the customer was looking at and using a GET parameter i can retrieve this product

I've tried to add the get parameter as follows:

# functions.php

function gpd_register_query_vars($vars)
{
    $vars[0] = 'my_product_id';
    return $vars;
}

add_filter('query_vars', 'gpd_register_query_vars');

Within my widget

class GPD_Get_Product_Widget extends WP_Widget
{
    // ...

    function widget($args, $instance)
    {
        global $wp_query;
        var_dump($wp_query->query_vars['my_super_unique_var']);

        extract($instance);
        //output code
        echo $args['before_widget'];
        include 'widget.php';
        echo $args['after_widget'];
    }
}

//function to register the widget
function gpd_get_product_widget()
{
    register_widget('GPD_Get_Product_Widget');
}

add_action('widgets_init', 'gpd_get_product_widget');

However, whenever i try to get the parameter it doesn't exist.

Wordpress isn't the easiest to navigate or work with. I'm really confused to why WP has made such a simple thing such as $_GET params so difficult.

Any help is much appreciated.


Solution

  • I found the answer and not entirely sure why this is but if you pass 2 params in your URL like so /my-page?a=1&b=2 and then use a plain old $_GET, you'll find that the the first element is a q and the second is your b param.

    array(2) {
      'q' =>
      string(29) "/request-a-quote/a=1"
      'b' =>
      integer(1) "2"
    }
    

    It looks like the first param is occupied by q (reserved var) by Wordpress and anything after that is additional params which are yours (unless they are reserved by WP).

    So if I was to build my URL like so:

    add_query_arg(['type' => 'holiday', 'product_id' => 12345], get_permalink($page_id) );
    

    You have to add a first param that will be ignored and then the second will be available as a $_GET.

    I might be doing something wrong but this works for me for now. Any help and pointers to what I'm doing wrong would be great - as this feels wrong but works.