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

How to Pass Extra Variables in WordPress URLs?

Susan Sarandon
Release: 2024-11-12 08:03:01
Original
993 people have browsed it

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>
    Copy after login
  • 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>
    Copy after login

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' );
Copy after login

On the page retrieving and processing the query variable:

$my_c = get_query_var('c');
Copy after login

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);
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template