How to retrieve URL parameters in a WordPress site?

Hey everyone! I’m working on a WordPress project and I’m stuck. I need to grab a parameter from the URL, but I’m not sure how to do it in WordPress. For example, I want to use something like mysite.com/?source=email and then get the ‘source’ value.

I’ve looked through the WordPress docs and found stuff about adding parameters with add_query_arg(), but nothing about getting them. I tried searching online too, but no luck.

Does anyone know how to do this? Maybe there’s a built-in WordPress function I’m missing? Or do I need to write some custom PHP in the functions.php file?

Any help would be awesome. Thanks in advance!

hey alexlee, i’ve dealt with this before. you can use the $_GET superglobal in php to grab url parameters. so for your example, you’d do something like:

$source = $_GET[‘source’];

just make sure to sanitize the input to avoid any security issues. hope this helps!

I’ve had a similar challenge in one of my WordPress projects. While the previous answers are valid, I found that using wp_get_raw_referer() can be incredibly useful, especially if you’re dealing with referral sources.

Here’s what I typically do:

$full_url = wp_get_raw_referer();
$parsed_url = parse_url($full_url);
parse_str($parsed_url[‘query’], $query_params);

$source = isset($query_params[‘source’]) ? sanitize_text_field($query_params[‘source’]) : ‘’;

This approach gives you more flexibility as it allows you to extract multiple parameters if needed. It’s also more WordPress-centric and handles potential edge cases better. Just remember to always sanitize the input to prevent any security vulnerabilities.

If you’re dealing with the current page URL instead of a referrer, you can use something like:

$current_url = home_url(add_query_arg(null, null));

And then parse it similarly. This has worked wonders for me in various scenarios, from tracking campaign sources to personalizing user experiences based on URL parameters.

In WordPress, you can indeed retrieve URL parameters using the $_GET superglobal, as mentioned. However, it’s generally recommended to use WordPress’s built-in functions for better compatibility and security. Try using get_query_var() like this:

$source = get_query_var(‘source’, ‘’);

This function allows you to specify a default value as the second parameter. If you need to add custom query variables, you’ll need to register them first using the ‘query_vars’ filter in your functions.php file. Remember to sanitize and validate any user input before using it in your code.