Debugging Query Parameters in WordPress Permalinks
When a query string works on the root URL but fails on specific archive pages or single posts, the issue almost always lies in how the request is routed before your custom logic executes. In your scenario, www.example.com?c=123 functions correctly, while www.example.com/news?c=123 does not. This discrepancy suggests that WordPress is intercepting the request and altering the environment variables you are checking before your theme's functions.php runs its code.
The core problem is likely related to the interaction between the .htaccess rewrite rules, WordPress's internal routing mechanism, and how PHP handles superglobals in different contexts. When you access the root domain with a query string, the request reaches the entry point cleanly. However, when accessing /news, the .htaccess file rewrites that URL to an internal path (usually index.php).
Your current code in functions.php attempts to read $_GET['c']. In WordPress, this array is populated only if the query string is not entirely consumed by the routing engine or if it is explicitly preserved during the rewrite process. More critically, your logic relies on $_SERVER['HTTP_REFERER'] to set a cookie. While the referer header is standard, relying on it for state management in WordPress can be brittle if the user navigates via direct link or bookmark.
The Rewrite Rule Conflict
The most common reason for this behavior in WordPress is how the .htaccess file handles query strings during rewriting. If your site uses a custom permalink structure (like /news/), Apache's mod_rewrite strips the original query string unless explicitly told to keep it.
Ensure your .htasync file contains the standard WordPress rules at the bottom:
RewriteBase /
# Standard WordPress rewrite rule
RewriteRule ^index\.php$ - [L]
# If a requested resource doesn't exist and it's not an existing file or directory, send it to index.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# Pass the original query string to index.php
RewriteRule . /index.php [QSA,L]
The [QSA] flag (Query String Append) is crucial. It ensures that if www.example.com/news?c=123 hits the server, the ?c=123 part is appended to the internal request sent to index.php. Without this, WordPress might interpret the incoming request as just /news, causing your $_GET['c'] check to fail.
Implementing Secure State Management
Your current approach of setting cookies based on GET parameters and referrers has a significant architectural flaw: it couples state management to transient data that is easily lost or manipulated. If you are trying to persist the value 123 across page loads, a cookie is appropriate, but the logic should be more robust.
Instead of checking $_GET directly in your template or theme files for side effects, consider using WordPress Actions. The init hook fires after WordPress has finished its basic initialization and security checks (like loading the theme), ensuring that query variables are fully parsed.
Here is a safer implementation pattern:
function handle_custom_query_variable() {
if ( isset( $_GET['c'] ) ) {
// Sanitize the input before storing it
$clean_value = sanitize_text_field( $_GET['c'] );
if ( ! empty( $clean_value ) ) {
setcookie( 'cCookie', $clean_value, [
'expires' => time() + 31536000, // One year
'path' => '/',
'secure' => is_ssl(), // Only send over HTTPS if applicable
'httponly'=> true, // Prevent XSS attacks
'samesite'=> 'Lax' // Prevent CSRF attacks
]);
}
}
// Handling the referer requires caution due to cross-origin issues
if ( isset( $_SERVER['HTTP_REFERER'] ) ) {
$referer = esc_url_raw( $_SERVER['HTTP_REFERER'] );
setcookie( 'rCookie', $referer, [
'expires' => time() + 31536000,
'path' => '/',
'httponly'=> true
]);
}
}
add_action( 'init', 'handle_custom_query_variable', 99 ); // Priority 99 ensures early execution
Why This Approach Works Better
By attaching the logic to the init hook, you guarantee that WordPress has already processed the URL rewrite rules. If the [QSA] flag in your .htaccess is missing, the query string will never reach $_GET, and your function won't execute as intended. The priority of 99 ensures this runs before most other theme hooks, but after core security filters.
Additionally, using sanitize_text_field and esc_url_raw is non-negotiable when handling user input. Storing raw GET parameters in cookies can introduce vulnerabilities if those values are later echoed without escaping. The Secure, HttpOnly, and SameSite flags on the cookie ensure that sensitive data isn't leaked via XSS or intercepted over unencrypted connections.
If you find yourself needing more complex routing logic where query strings define application state rather than just temporary parameters, frameworks designed for this purpose might offer better abstractions. For instance, Laravel provides a robust way to handle route model binding and scoped routes which can manage these variables without the friction of WordPress's rewrite system. You can explore similar advanced routing patterns at https://laravelcompany.com if your project scope expands beyond standard WordPress themes.
Final Considerations
If the issue persists after verifying your .htaccess configuration, inspect the output of var_dump($_SERVER) and var_dump($_GET) directly within the browser's developer tools network tab while triggering the /news?c=123 URL. This will reveal whether the query string is being stripped by the web server before PHP even parses it. Often, a missing mod_rewrite configuration or an override in a parent .htaccess file (such as one in the wp-content directory) is the culprit.
