Pass GET params to URL from a main menu item

by puk789   Last Updated September 08, 2018 17:08 PM

I have a booking form on page "Training" and I want it to be pre-filled with logged in user's details. For that I need to pass those details (name and email) to URL and the form should automatically take those details and insert them into corresponding form fields (that's what I was advised to do by the plugin creator).

So I tried adding a random button inside a random page pointing to the Training page with those 2 parameters added:

<a href="<?php echo esc_url( add_query_arg( array( 
                'name' => $user_name,
                'email' => $user_email
                ), site_url( '/trainings/' )))?>">Go to trainings</a>

Now this alone opens the following URL:

http://mysite/trainings/?name=examplename&email=exampleemail

And throws 'Not found' error. Why can this be?

Moreover, even if this worked, I would need to pass those 2 parameters to URL via a regular main menu link, not a random button. How can I go about this? I tried adding the above <a> code as a custom link in to the main menu but didn't work.



Answers 1


The 404 issue is because name is a WordPress query var. Adding that in the URL causes WordPress to query for a post with slug that matches whatever is in the name field, instead of your page. Change your form field names to something you know will be unique. This is a good practice for everything you have to name- form fields, functions, etc..

As for your menu item question, you can use the nav_menu_link_attributes filter to alter the href for a specific menu item. Here we check if Trainings is the title of the menu item, and add the GET params if that is the case:

function wpd_add_logged_in_get_params(){
    if( is_user_logged_in() ){
        add_filter( 'nav_menu_link_attributes', function( $atts, $item ){
            if( 'Trainings' == $item->title ){
                $current_user = wp_get_current_user();
                $atts['href'] = esc_url(
                    add_query_arg(
                        array( 
                            'wpd_name' => $current_user->display_name,
                            'wpd_email' => $current_user->user_email
                        ),
                        $atts['href']
                    )
                );
            }
            return $atts;
        }, 10, 2 );
    }
}
add_action( 'template_redirect', 'wpd_add_logged_in_get_params' );
Milo
Milo
September 08, 2018 18:07 PM

Related Questions



help me remove this additional parameter in url

Updated December 31, 2016 08:03 AM

Pass post title as URL parameter

Updated April 21, 2017 12:08 PM

Use URL parameter to create dynamic content

Updated May 25, 2018 14:08 PM