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

How to Pass Extra Variables in WordPress URLs?

Susan Sarandon
Susan SarandonOriginal
2024-11-12 08:03:01950browse

How to Pass Extra Variables in WordPress URLs?

Passing Extra Variables in WordPress URLs

When attempting to pass an additional variable in a WordPress URL, issues may arise when the URL contains additional information after the root domain. To resolve this, employ the following approach:

1. Utilizing WordPress Functions

Instead of interacting with superglobals, utilize the following WordPress functions:

  • add_query_arg(): Creates a URL with the custom query variable.
  • query_vars: Modifies WordPress's recognized query variables (applicable only on the front-end).
  • get_query_var(): Retrieves the value of the custom query variable.

2. Example Implementation

On the page creating the link:

  • Add the query variable to back-to-page link:

    <a href="<?php echo esc_url(add_query_arg('c', $my_value_for_c)); ?>"></a>
  • Link to a different page:

    <a href="<?php echo esc_url(add_query_arg('c', $my_value_for_c, site_url('/some_other_page/'))); ?>"></a>

In your functions.php or plugin file (front-end only):

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

On the page retrieving and processing the query variable:

$my_c = get_query_var('c');

3. Back End Considerations

On the back end, the wp() function is not executed, so you cannot rely on the WP Query. Instead, inspect the $_GET superglobal:

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

By adhering to these recommendations, you can effectively pass additional variables in WordPress URLs, both on the front-end and back-end.

The above is the detailed content of How to 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