Query String with WooCommerce
-
Hi All,
First a bit of a warning. I’m very much a newb when it comes to wordpress and php, so if you are able to offer assistance to the below, please use small words if possible :-).On to the problem. I’ve got a wordpress website and am using WooCommerce to sell registrations for applications that I develop. To streamline the registration process, I would like users to be able to click a registration button in the application and be taken directly to my WooCommerce checkout page with the registration product already loaded in the cart and a username (generated by the application) entered automatically in the checkout page’s username field (which I’ve added).
What I’ve got so far is, when the user clicks on the applications registration button, the application sends the user in their browser to a URL that looks like:
http://www.mysite.com/checkout/?add-to-cart=532&username=myname
In my function.php file I’m redirecting to the checkout when adding to cart, so this opens the checkout page with the product id = 532 already in the cart. Perfect.
To make the username variable public, I added the following to my functions.php file:
add_filter( 'query_vars', 'add_query_vars_filter' ); function add_query_vars_filter( $vars ){ $vars[] = "username"; return $vars; }To capture the username from the query string and enter it in a created username field, I also added the following to my functions.php file:
add_filter( 'woocommerce_checkout_fields' , 'custom_override_checkout_fields' ); function custom_override_checkout_fields( $fields ) { $thename = get_query_var( 'username', 'defaultName' ); $fields['billing']['billing_username'] = array( 'label' => __($label, 'woocommerce'), 'placeholder' => _x($placeholder, 'placeholder', 'woocommerce'), 'required' => true, 'class' => array('form-row-wide'), 'clear' => true, 'default' => $thename ); return $fields; }Unfortunately, ‘defaultName’ is entered in the username field. If I remove the “add-to-cart=532” from the URL, then ‘myname’ is entered. I think that the problem is that by the time the checkout page opens, “username=myname” is stripped from the URL. It seems I have to use $thename = get_query_var( ‘username’, ‘defaultName’ ) earlier in the process of opening the checkout page (and one of the problems is that I don’t fully understand this process) and somehow make it accessible in the custom_override_checkout_fields function in my functions.php file. So the question is how do I accomplish this?
Thanks in advance for any help.
The topic ‘Query String with WooCommerce’ is closed to new replies.