"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > WordPress URL pass additional variable method

WordPress URL pass additional variable method

Posted on 2025-04-15
Browse:534

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:

    ">
  • Link to a different page:

    ">

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.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3