Reputation: 805
On my WordPress page I have created a shortcode function which gets a parameters from the URL of the post. So, I have created this simple function and added the following code to the theme's file function.php
:
function getParam($param) {
if ($param !== null && $param !== '') {
echo $param;
} else {
echo "Success";
}
}
add_shortcode('myFunc', 'getParam');
And I know I have to add this shortcode to posts and pages using (in my case) [myFunc param='']
.
Usually, I would get the value of the parameter from the URL using <?php $_GET['param'] ?>
, but in this case I don't know how to send this PHP code to the shortcode function.
For example, I doubt I can write [myFunc param=$_GET['param']]
.
Upvotes: 3
Views: 5588
Reputation: 34
Do it this way:
function getParam($data)
{
$var = $_GET[$data['param']];
if ($var !== null && $var !== '')
{
echo "True: " . $var;
}
else echo "False: " . $var;
}
And call it by: [myFunc param=whatever]
You shouldn't call a function in the shortcode.
For better understanding, I changed your code just a little bit, but beware this is not secure and clean.
Upvotes: 0
Reputation: 2943
If you need get the parameters you can:
function getParam($arg) {
if (isset($arg) &&
array_key_exists('param', $arg ) &&
$arg['param'] != '')
{
return $_GET[$arg['param']]; // OR get_query_var($arg['param']);
}
else
return "Success";
}
add_shortcode('name', 'getParam');
Upvotes: 0
Reputation: 8329
A shortcode like this:
[myFunc funcparam="param"]
Is not needed here, unless the called parameter is changing with the posts.
Let's say you have this URL:
http://example.com?param=thisparam
To get the value of 'param' by using the shortcode described above, your function in functions.php should look something like this:
function sc_getParam() {
// Get parameter(s) from the shortcode
extract( shortcode_atts( array(
"funcparam" => 'funcparam',
), $atts ) );
// Check whether the parameter is not empty AND if there is
// something in the $_GET[]
if ( $funcparam != '' && isset( $_GET[ $funcparam ] ) ) {
// Sanitizing - this is for protection!
$thisparam = sanitize_text_field( $_GET[ $funcparam ] );
// Returning the value from the $_GET[], sanitized!
return $thisparam;
}
else {
// Something is not OK with the shortcode function, so it
// returns false
return false;
}
}
add_shortcode( 'myFunc', 'sc_getParam' );
Look up these references:
WordPress Shortcodes: A Complete Guide - tutorial on creating shortcodes
Validating Sanitizing and Escaping User Data - sanitizing
Upvotes: 1