WordPress wp_parse_url() vs wp_parse_str() - Complete Comparison Guide
Mahesh Waghmare WordPress provides two similar-sounding functions for parsing: wp_parse_url() and wp_parse_str(). While their names are similar, they serve completely different purposes. Understanding when to use each is crucial for WordPress development.
This guide explains both functions in detail, their differences, use cases, and best practices.
Introduction
Both functions are WordPress wrappers around PHP’s native functions, but they add WordPress-specific enhancements:
- wp_parse_url(): Parses a URL into its components (scheme, host, path, query, etc.)
- wp_parse_str(): Parses a query string into an associative array
Why WordPress Versions?
- Better error handling
- Consistent behavior across PHP versions
- WordPress-specific enhancements
- Backward compatibility
wp_parse_url() Function
wp_parse_url() is a WordPress wrapper for PHP’s parse_url() function. It parses a URL and returns its components.
Syntax
wp_parse_url( string $url, int $component = -1 ): mixed
Parameters
$url: The URL to parse$component: Optional. Specific component to retrieve (PHP_URL_SCHEME, PHP_URL_HOST, etc.)
Return Value
- Returns array of URL components, or
- Returns specific component if
$componentis specified, or - Returns
falseon failure
URL Components
A URL can be broken into these components:
- scheme: http, https, ftp, etc.
- host: Domain name or IP
- port: Port number
- user: Username
- pass: Password
- path: Path component
- query: Query string (after ?)
- fragment: Fragment (after #)
Examples
Parse Full URL:
$url = 'https://example.com:8080/path/to/page?param=value#section';
$parsed = wp_parse_url($url);
/*
Returns:
Array (
[scheme] => https
[host] => example.com
[port] => 8080
[path] => /path/to/page
[query] => param=value
[fragment] => section
)
*/
Get Specific Component:
$url = 'https://example.com/page';
$host = wp_parse_url($url, PHP_URL_HOST);
// Returns: 'example.com'
$scheme = wp_parse_url($url, PHP_URL_SCHEME);
// Returns: 'https'
$path = wp_parse_url($url, PHP_URL_PATH);
// Returns: '/page'
Real-World Example:
function get_domain_from_url($url) {
$parsed = wp_parse_url($url);
return isset($parsed['host']) ? $parsed['host'] : false;
}
$domain = get_domain_from_url('https://www.example.com/page');
// Returns: 'www.example.com'
wp_parse_str() Function
wp_parse_str() is a WordPress wrapper for PHP’s parse_str() function. It parses a query string into variables or an array.
Syntax
wp_parse_str( string $string, array &$array ): void
Parameters
$string: The query string to parse$array: Reference to array where parsed values will be stored
Return Value
- Returns
void(modifies array by reference) - Parsed values are stored in the
$arrayparameter
Query String Format
Query strings are in the format: key1=value1&key2=value2&key3=value3
Examples
Basic Usage:
$query_string = 'name=John&age=30&city=NewYork';
$params = array();
wp_parse_str($query_string, $params);
/*
$params now contains:
Array (
[name] => John
[age] => 30
[city] => NewYork
)
*/
With URL Encoding:
$query = 'name=John+Doe&email=john%40example.com';
$params = array();
wp_parse_str($query, $params);
/*
$params:
Array (
[name] => John Doe
[email] => john@example.com
)
*/
Nested Parameters:
$query = 'user[name]=John&user[age]=30&settings[theme]=dark';
$params = array();
wp_parse_str($query, $params);
/*
$params:
Array (
[user] => Array (
[name] => John
[age] => 30
)
[settings] => Array (
[theme] => dark
)
)
*/
Real-World Example:
function parse_custom_query($url) {
$parsed_url = wp_parse_url($url);
if (!isset($parsed_url['query'])) {
return array();
}
$params = array();
wp_parse_str($parsed_url['query'], $params);
return $params;
}
$url = 'https://example.com/page?category=tech&sort=date&limit=10';
$query_params = parse_custom_query($url);
/*
$query_params:
Array (
[category] => tech
[sort] => date
[limit] => 10
)
*/
Key Differences
Purpose
wp_parse_url():
- Parses entire URL structure
- Returns URL components (scheme, host, path, etc.)
- Used for URL manipulation and analysis
wp_parse_str():
- Parses only the query string portion
- Converts query string to associative array
- Used for processing URL parameters
Input
wp_parse_url():
- Takes full URL:
https://example.com/page?param=value
wp_parse_str():
- Takes query string only:
param=value&other=data
Output
wp_parse_url():
- Returns array of URL components
- Can return specific component
- Returns
falseon failure
wp_parse_str():
- Modifies array by reference
- Returns
void - Always succeeds (empty array if invalid)
Use Case
wp_parse_url():
- Extract domain from URL
- Get path component
- Check URL scheme (http vs https)
- Analyze URL structure
wp_parse_str():
- Process GET parameters
- Parse form data
- Handle query string parameters
- Extract URL parameters
Use Cases and Examples
Combining Both Functions
Often, you’ll use both functions together:
function get_url_parameters($url) {
// First, parse the URL to get components
$parsed = wp_parse_url($url);
// Check if query string exists
if (!isset($parsed['query'])) {
return array();
}
// Then, parse the query string
$params = array();
wp_parse_str($parsed['query'], $params);
return $params;
}
$url = 'https://example.com/products?category=electronics&sort=price&page=2';
$params = get_url_parameters($url);
/*
$params:
Array (
[category] => electronics
[sort] => price
[page] => 2
)
*/
WordPress-Specific Examples
Get Current URL Components:
$current_url = home_url(add_query_arg(array(), $wp->request));
$parsed = wp_parse_url($current_url);
$scheme = $parsed['scheme']; // http or https
$host = $parsed['host']; // domain.com
$path = $parsed['path']; // /current/path
Process Custom Query Vars:
function handle_custom_query_vars() {
$query_string = $_SERVER['QUERY_STRING'];
$params = array();
wp_parse_str($query_string, $params);
if (isset($params['custom_param'])) {
// Process custom parameter
$value = sanitize_text_field($params['custom_param']);
// Use the value...
}
}
Build URL from Components:
function build_url_from_components($components) {
$url = '';
if (isset($components['scheme'])) {
$url .= $components['scheme'] . '://';
}
if (isset($components['host'])) {
$url .= $components['host'];
}
if (isset($components['port'])) {
$url .= ':' . $components['port'];
}
if (isset($components['path'])) {
$url .= $components['path'];
}
if (isset($components['query'])) {
$url .= '?' . $components['query'];
}
if (isset($components['fragment'])) {
$url .= '#' . $components['fragment'];
}
return $url;
}
Validate and Sanitize URL Parameters:
function safe_get_url_params($url) {
$parsed = wp_parse_url($url);
if (!isset($parsed['query'])) {
return array();
}
$params = array();
wp_parse_str($parsed['query'], $params);
// Sanitize all parameters
$sanitized = array();
foreach ($params as $key => $value) {
$sanitized[sanitize_key($key)] = sanitize_text_field($value);
}
return $sanitized;
}
Comparison Table
| Feature | wp_parse_url() | wp_parse_str() |
|---|---|---|
| Purpose | Parse URL structure | Parse query string |
| Input | Full URL | Query string only |
| Output | Array of components | Modifies array by reference |
| Return Type | Array or string or false | void |
| Use Case | URL analysis, component extraction | Parameter processing |
| Example Input | https://example.com/page?p=1 | p=1&q=search |
| Example Output | ['scheme' => 'https', 'host' => 'example.com', ...] | ['p' => '1', 'q' => 'search'] |
Best Practices
1. Always Check Return Values
wp_parse_url():
$parsed = wp_parse_url($url);
if ($parsed === false) {
// Handle error
return;
}
if (!isset($parsed['host'])) {
// Invalid URL
return;
}
wp_parse_str():
$params = array();
wp_parse_str($query_string, $params);
if (empty($params)) {
// No parameters found
return;
}
2. Sanitize Input
// Always sanitize URLs and query strings
$url = esc_url_raw($user_input);
$parsed = wp_parse_url($url);
$params = array();
if (isset($parsed['query'])) {
wp_parse_str($parsed['query'], $params);
// Sanitize parameters
foreach ($params as $key => $value) {
$params[$key] = sanitize_text_field($value);
}
}
3. Use WordPress Functions
Prefer WordPress functions over PHP native:
- Better error handling
- Consistent behavior
- WordPress enhancements
- Backward compatibility
4. Handle Edge Cases
function safe_parse_url($url) {
if (empty($url)) {
return false;
}
$parsed = wp_parse_url($url);
if ($parsed === false) {
return false;
}
// Ensure required components exist
if (!isset($parsed['host'])) {
return false;
}
return $parsed;
}
5. Combine with add_query_arg()
// WordPress way to add query parameters
$url = add_query_arg(array(
'page' => 2,
'sort' => 'date'
), home_url('/products'));
// Then parse if needed
$parsed = wp_parse_url($url);
Conclusion
wp_parse_url() and wp_parse_str() serve different purposes:
- wp_parse_url(): For parsing and analyzing URL structure
- wp_parse_str(): For processing query string parameters
Key Takeaways:
- Use
wp_parse_url()to extract URL components - Use
wp_parse_str()to process query parameters - Often used together: parse URL first, then parse query string
- Always sanitize input and validate output
- Prefer WordPress functions over PHP native for consistency
Understanding both functions and when to use each will make your WordPress development more efficient and your code more robust.
Written by Mahesh Waghmare
I bridge the gap between WordPress architecture and modern React frontends. Currently building tools for the AI era.
Follow on Twitter →