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

How to Pass Additional Variables in URLs with WordPress?

Linda Hamilton
Linda HamiltonOriginal
2024-11-10 17:08:03663browse

How to Pass Additional Variables in URLs with WordPress?

Passing Additional Variables in URLs with WordPress

WordPress provides a robust way to pass additional variables within URLs, allowing for dynamic content and functionality. However, certain issues may arise when attempting to include variables in URLs that contain more than just the website root.

Solution Using WordPress Functions

To resolve this issue and seamlessly pass variables in URLs, utilize the following three WordPress functions:

  1. add_query_arg(): Generates the URL with the new query variable.
  2. query_vars filter: Modifies the list of publicly available query variables recognized by WordPress (applicable only on the "front-end" of your website).
  3. get_query_var(): Retrieves the value of your custom query variable from the URL.

Example

On the page where you need to create the link:

  • If it's a link to the current page (appending a query variable):
<a href="<?php echo esc_url( add_query_arg( 'c', $my_value_for_c ) )?>"></a>
  • If it's a link to another 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 file (executed only on the front-end):

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 the query variable:

$my_c = get_query_var( 'c' );

Back-End (wp-admin)

Accessing query variables in wp-admin requires a different approach since the WordPress Query is not executed in this context. Instead, examine the $_GET superglobal using:

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

By employing these methods, you can effortlessly pass additional variables in WordPress URLs and access them both on the front-end and back-end of your website.

The above is the detailed content of How to Pass Additional Variables in URLs with WordPress?. 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