Home >Backend Development >PHP Tutorial >How do I Pass Extra Variables in WordPress URLs?

How do I Pass Extra Variables in WordPress URLs?

Linda Hamilton
Linda HamiltonOriginal
2024-11-11 06:23:02591browse

How do I Pass Extra Variables in WordPress URLs?

Passing Extra Variables in WordPress URLs

In WordPress, you may encounter difficulties passing additional variables through URLs. For instance, trying to add "&c=123" to "/news" may only work for the root URL (www.example.com?c=123) but fail if the URL contains additional information (www.example.com/news?c=123).

To address this issue, WordPress provides three essential functions:

  • add_query_arg(): Creates URLs with new query variables.
  • query_vars filter: Modifies WordPress's publicly known query variables.
  • get_query_var(): Retrieves the value of custom query variables in URLs.

Example:

. On the page where you create the link or set the query variable:

  • To add a query variable to a link back to the current page:
<a href="<?php echo esc_url(add_query_arg('c', $my_value_for_c)); ?>">
  • To add a query variable to a link to another page:
<a href="<?php echo esc_url(add_query_arg('c', $my_value_for_c, site_url('/some_other_page/'))); ?>">

. In functions.php or a plugin file:

function add_custom_query_var($vars) {
    $vars[] = "c";
    return $vars;
}
add_filter('query_vars', 'add_custom_query_var');

. On the page where you want to retrieve and use the query variable:

$my_c = get_query_var('c');

On the Back End (wp-admin)

When accessing the backend (wp-admin), the main WP Query is not executed, and thus query variables are unavailable. Instead, you should use the following approach:

$my_c = filter_input(INPUT_GET, "c", FILTER_SANITIZE_STRING);

The above is the detailed content of How do I Pass Extra Variables in WordPress URLs?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn