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. How can it be done?
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.
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' );
When passing parameters through the URL you're able to retrieve the values as GET parameters.
Use this:
$variable = $_GET['param_name'];
//Or as you have it
$ppc = $_GET['ppc'];
It is safer to check for the variable first though:
if (isset($_GET['ppc'])) {
$ppc = $_GET['ppc'];
} else {
//Handle the case where there is no parameter
}
Here's a bit of reading on GET/POST params you should look at: http://php.net/manual/en/reserved.variables.get.php
EDIT: I see this answer still gets a lot of traffic years after making it. Please read comments attached to this answer, especially input from #emc who details a WordPress function which accomplishes this goal securely.
You can try this function
/**
* Gets the request parameter.
*
* #param string $key The query parameter
* #param string $default The default value to return if not found
*
* #return string The request parameter.
*/
function get_request_parameter( $key, $default = '' ) {
// If not request set
if ( ! isset( $_REQUEST[ $key ] ) || empty( $_REQUEST[ $key ] ) ) {
return $default;
}
// Set so process it
return strip_tags( (string) wp_unslash( $_REQUEST[ $key ] ) );
}
Here is what is happening in the function
Here three things are happening.
First we check if the request key is present or not. If not, then just return a default value.
If it is set, then we first remove slashes by doing wp_unslash. Read here why it is better than stripslashes_deep.
Then we sanitize the value by doing a simple strip_tags. If you expect rich text from parameter, then run it through wp_kses or similar functions.
All of this information plus more info on the thinking behind the function can be found on this link https://www.intechgrity.com/correct-way-get-url-parameter-values-wordpress/
In the call back function, use the $request parameter
$parameters = $request->get_params();
echo $parameters['ppc'];
Related
Codeigniter has a syntax for url parameter passing for functions inside the controller.
If a function for example:
function index($id){
$this->model->get_user($id);
}
Assuming that this function is called without supplying the ID namely called as
ProjectName/Controller/index
it will return an error as it expects a parameter.
Is there a way to check if a parameter exists.
No there is not a way to check if one exists per-say as that error happens before the controller has a chance to run code. ie. before the class method executes.
That said there is a simple workaround for this: You can supply a default value and check for that for example
function index($id = null){
if( is_null($id) ){
///do something - like show a pretty error, or redirect etc...
}else{
$this->model->get_user($id);
}
}
This way when no parameter is supplied the ID will be null, this is fairly safe ( when using null ) because you can never supply null as part of the url path even doing this
www.mysite.com/index/null //or however the url works out in your case
Will supply null as a string, because everything in the url comes through as a string. So 'null' as a string is not in fact null it's just the word null. If that makes sense. So given that null could never be supplied and only happens if no other value is supplied.
In this case it may be worth casting the input to a int or further checking if it's an improper value.
This could be done several ways:
Casting:
function index($id = null){
if( is_null($id) ){
///do something - like show a pretty error, or redirect etc...
}else{
$this->model->get_user((int)$id);
//cast to int, things that are not INT or string equivalents become 0, which should not find a user as it would look for ID = 0
}
}
By Regx check:
function index($id = null){
if( is_null($id) ){
///do something - like show a pretty error, or redirect etc...
}else if( preg_match('/^[^\d]+$/', $id )){
// not an int ( contains anything other than a digit )
}else{
$this->model->get_user($id);
}
}
Cheers.
I am using the below code in functions.php to add custom query variables to my WordPress project.
<?php
function add_custom_query_var( $vars ){
$vars[] = "brand";
return $vars;
}
add_filter( 'query_vars', 'add_custom_query_var' );
?>
And then on the content page I am using:
<?php echo $currentbrand = get_query_var('brand'); ?>
So now I can pass a URL like:
http://myexamplesite.com/store/?brand=nike
and get nike in result.
How can I pass multiple values for a brand. So I would like to have 3 values for brand say, nike, adidas and woodland.
I have tried the following and none of them works:
http://myexamplesite.com/store/?brand=nike&brand=adidas&brand=woodland
It just returns the last brand, in this case woodland.
http://myexamplesite.com/store/?brand=nike+adidas+woodland
This returns all three with spaces. I kind of think this is not the correct solution. So may be there is a correct way to pass multiple values for a query variable and retrieve them in an array may be so that a loop can be run.
Usually you would pass the parameter like ?brand[]=unresponsibleCompany1&brand[]=otherBrandThatDoesNotCareMuch&brand[]=bunchOfCriminals .
In your WordPress PHP code, then get_query_var( 'brand' ) will return you an Array.
Everything else sounds like a relatively cheap but costy workaround.
You will need to pass query parameters in this way;
brand1=nike&brand2=adidas&brand3=woodland
So, different key for each brand
On the page, recieving values
$params = $_GET;
$brands = array();
foreach($params as $k=>$v) {
if(substr($k,0,5)=="brand") {
$brands[] = $v;
}
}
Alternatively
Using your 2nd method
http://myexamplesite.com/store/?brand=nike+adidas+woodland
$brands = explode(" ", $_GET['brand']);
Alternative method looks easier 🙂
I have a javascript client passing a parameter to a server function (I'm using ExtJS Direct). Sometimes the client sends a single object, sometimes it sends an array of objects.
Currently I'm using this EnsureArray function to ensure the parameter is an array, and then I do foreach:
// Wraps a non array variable with an array.
function EnsureArray( &$aVar )
{
if ( !is_array( $aVar ) )
$var = array( $aVar );
}
function Destroy( $aRecords )
{
// $aRecords might be a single object or an array of objects. Ensure it's wrapped as an array.
$this->EnsureArray( $aRecords );
foreach ( $aRecords as $aRecord )
{
sql( "UPDATE Groups SET deleted = true WHERE id = $aRecord->id LIMIT 1" );
}
return array(
'success' => true,
);
}
Is there a trick, neater way, one line that can do the same?
Edit: Since posting this question, I've found that ExtJS has an option to send all records wrapped in array.
You could try the following, instead of the function:
$aRecords = is_array($aRecords) ? $aRecords : array($aRecords);
That's probably the best way tbh, if you're not going to enforce that you're always being sent an array.
I would make the function Destroy require arrays as its parameter:
function Destroy(array $aRecords) { ... }
The client should then also always send arrays. If, for whatever reason, that is not possible, the code that is receiving the (non-)array from the client and is passing it on to Destroy() needs to be responsible for passing it along as an array, because it's the interface between the (non-compliant) client and the standardized function.
There's probably going to be one endpoint for each possible action the client can call, so you don't even need to figure out whether the data is an array or not, you simply know. I.e.:
// someaction.php
include 'destroy.php';
$data = json_decode($_POST['data']);
Destroy($data);
but:
// anotheraction.php
include 'destroy.php';
$data = json_decode($_POST['data']);
Destroy(array($data));
If the client erratically sends different formats to the same action, fix the client.
Simply typecast the variable to an array:
function Destroy( $aRecords )
{
foreach ( (array)$aRecords as $aRecord )
{
sql( "UPDATE Groups SET deleted = true WHERE id = $aRecord->id LIMIT 1" );
}
return array(
'success' => true,
);
}
See http://php.net/manual/en/language.types.type-juggling.php
I'm building a backend component (1.6 / 1.7 / 2.5) where I need to pass a variable from another view into a field in a new record. Variable passing is working fine.
My problem is using getInput().
To start with different doc pages have different amounts and formatting of parameters - confusing! For example:
http://docs.joomla.org/API16:JForm/getInput: getInput($name, $group= '_default', $formControl= '_default', $groupControl= '_default', $value=null)
vs
http://docs.joomla.org/JForm::getInput/1.6:
public function getInput (
$name
$group=null
$value=null
)
The problem:
I just need to pass a variable as a default value, something like:
echo $this->form->getInput('id', $value=$this->userID );?>
The above code makes the input field disappear. If I take out the $value=$this->userID the input field shows up though obviously doesn't have any default value. I've also tried:
$value=$this->userID;
echo $this->form->getInput('id', $value );
And same problem, the input field goes away. I tried a few other variations but basically if I try to put anything else within getInput() it doesn't work nor can I find any good working examples of how to use these other parameters.
What am I doing wrong?
Thanks!
According to the source, this is the correct API:
getInput($name, $group = null, $value = null)
And getInput() just calls getField():
getField($name, $group = null, $value = null)
Which means you should be doing this to set a default value:
echo $this->form->getInput('id', null, $this->userID ); // Returns the $field->input String
Or:
$field = $this->form->getField('id', null, $this->userID ); // Returns the JFormField object
I have a simple link like so: Accept
The idea is that this will run a function called wp_accept_function and pass in the id of 10 how do I do this? Thanks
Here is the code I have so far, but I feel I'm going wrong and need to pass the number into the function and then be able to use it within the function. Thanks
if ( isset ( $_GET ['wp_accept_function'] ) )
{
function wp_accept_favor ( $id )
{
// JAZZ
}
}
I think you want this:
First you need to define the function.
function wp_accept_favor($id) {
// do something
}
Then, you have to check if the parameter is set and call the function.
if (isset($_GET['wp_accept_function'])) {
// call the function passing the id casted to an integer
wp_accept_favor((int)$_GET['wp_accept_function']);
}
The cast to (int) is for avoid passing a non-integer type for wp_accept_favor() function, but you can handle it as you want.
If you are trying to build something generic...
// Add a white list of functions here which can be called via GET.
$safeFunctions = array('wp_accept_function');
foreach($_GET as $function => $argument) {
if (in_array($function, $safeFunctions)
AND function_exists($function)) {
$function($argument);
}
}
However, make sure you have a whitelist of safe functions, otherwise your app will no doubt have security issues.