How to retrieve URL query parameters in WordPress

I need help getting URL parameters in my WordPress website. Let me explain what I’m trying to do.

I want to capture values from URLs like mysite.com/?campaign=social when users visit my site. I plan to add this code to my theme’s functions.php file, but I’m not sure about the correct approach in WordPress.

I’ve seen plenty of tutorials showing how to add parameters to URLs with add_query_arg(), but I can’t find clear examples of how to actually read and use these parameters once they’re in the URL. What’s the proper WordPress way to handle this?

hey! just use $_GET[‘campaign’] to grab the parameter. works fine in wordpress - don’t overcomplicate it. i use this in my themes all the time.

Yeah, $_GET works but I’d go with get_query_var() instead. It’s more WordPress-friendly and handles sanitization automatically. Just use $campaign = get_query_var('campaign'); but you’ll need to register custom query variables first with add_query_vars_filter() in functions.php. If you stick with $_GET, wrap it in sanitize_text_field($_GET['campaign']) - never trust user input. I’ve used this setup for UTM parameters and custom campaigns for years, no problems.

There’s another approach you might want to try. Use the global $wp_query object to grab URL parameters without registering custom query vars. Just do global $wp_query; $campaign = $wp_query->get('campaign'); - works great for most situations. I use this all the time with custom post type archives or when I need parameters in template files. It plays nicer with WordPress’s query system than hitting $_GET directly. Don’t forget to sanitize the data afterward though, depending on what you’re doing with it.