Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting a parameter from a URL in WordPress

Tags:

php

wordpress

I am trying to pass a parameter to a WordPress site using a URL - for instance:

www.fioriapts.com/?ppc=1 will be the URL.

I am intending to write a function in the functions.php file but the mechanics of how to extract a parameter in WordPress is beyond me. I am finding a lot of examples on how to add a parameter to a URL using the function add_query_arg() but have found nothing on how to extract a parameter. Thanks in advance for any help.

like image 455
Chuck Avatar asked Nov 30 '12 20:11

Chuck


People also ask

How can I get parameters from a URL string?

The parameters from a URL string can be retrieved in PHP using parse_url() and parse_str() functions. Note: Page URL and the parameters are separated by the ? character. parse_url() Function: The parse_url() function is used to return the components of a URL by parsing it.

How do you separate parameters in a URL?

URL parameters are made of a key and a value, separated by an equal sign (=). Multiple parameters are each then separated by an ampersand (&).


1 Answers

Why not just use the WordPress get_query_var() function? WordPress Code Reference

// Test if the query exists at the URL if ( get_query_var('ppc') ) {      // If so echo the value     echo get_query_var('ppc');  } 

Since get_query_var can only access query parameters available to WP_Query, in order to access a custom query var like 'ppc', you will also need to register this query variable within your plugin or functions.php by adding an action during initialization:

add_action('init','add_get_val'); function add_get_val() {      global $wp;      $wp->add_query_var('ppc');  } 

Or by adding a hook to the query_vars filter:

function add_query_vars_filter( $vars ){   $vars[] = "ppc";   return $vars; } add_filter( 'query_vars', 'add_query_vars_filter' ); 
like image 145
Marc Avatar answered Sep 22 '22 00:09

Marc