Add WordPress shortcode which sends parameters - php

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']].

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

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');

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.

Related

Are multiple 'IF Statements' correct to use?

I have a two column page design in WordPress.
I would like to display a different widget based upon the allocated WordPress category in the right hand side column using a functions command.
My question is this: is my approach the 'correct method?' I have 3 sets of arrays in an "IF Statement"
I should add that it works!
But - I want to make sure that it is correctly done:
function my_custom_sidebar_display( $sidebar ) {
// Return a different sidebar for different categories
if ( in_category(array('Apples','Pears','Peaches')) ) {
return 'sidebar-fruit';
}
if ( in_category(array('potatoes','carrots','celery')) ) {
return 'sidebar-vegetables';
}
}
if ( in_category(array('monkeys','rhino','cheetah')) ) {
return 'sidebar-animals';
}
// Return theme defined sidebar area
else {
return $sidebar;
}
}
add_filter( 'ocean_get_sidebar', 'my_custom_sidebar_display' );
For readability later and for other developers, else if highlights that only one statement can be true, which otherwise is not 100% obvious.
Your function would change to something like this:
function my_custom_sidebar_display( $sidebar ) {
// Return a different sidebar for different categories
if ( in_category(array('Apples','Pears','Peaches')) ) {
return 'sidebar-fruit';
} else if ( in_category(array('potatoes','carrots','celery')) ) {
return 'sidebar-vegetables';
} else if ( in_category(array('monkeys','rhino','cheetah')) ) {
return 'sidebar-animals';
} else { // Return theme defined sidebar area
return $sidebar;
}
}
Normally, else if has the advantage of being more efficient. Imagine, as suggested in the comments, you do not return immediately, but save the value in an intermediary variable and return that variable in the end:
if ($letter === 'a') { $value = "1";}
if ($letter === 'b') { $value = "2";}
if ($letter === 'c') { $value = "3"; }
return $value;
That way all 3 conditions will be checked, even though you know that only one of them can be true.
(This is just an illustration, I also think it's fine to just return immediately instead of populating another variable)

Ajax and func_get_args()

Is it possible to use php's func_get_args() to catch 'post(ed)' data from an Ajax function call? (Currently using json to post data).
Hypothetical Ajax call posting data:
.
url: '.../.../...?action=function'
data: { someString: someString }
.
.
php:
function() {
$arg_list = func_get_args();
foreach( $arg_list as ....) {
.
.
}
}
i'm currently using isset( $_POST['someString'] ) but I was wondering if i can achieve the same using func_get_args().
Currently, func_get_args isn't catching anything from the ajax call. The 'post' line is directly below this chunk of code and is verifying that ajax has correctly sent the function the correct data. However, func_get_args isn't actually displaying anything on a var_dump. What am i not doing?
Many Thanks
Unfortunately not. func_get_args() looks for function arguments in php stack, while $_POST and $_GET look for http request header parameters.
But if you just want to iterate through $_POST parameters without knowing their names, try this:
foreach( $_POST as $pars ) {
if( is_array( $pars ) ) {
foreach( $pars as $par ) {
echo $par;
}
}
else { echo $pars;
}
}
You should try something like that :
function myAjaxFunction() {
$args = $_POST;
if (sizeof($args) > 0)
{
foreach ($arg_list as $arg) {
//
}
}
}

Access to a variable function from another function in WordPress

there's a problem, I can not understand what I'm doing wrong ..
I want to get the value of the function of the other features in WordPress ..
This code replaces some parts of the code ..
I want to get the value of the argument variable words (it needs to go $attr['words']) and then use the other functions (new_quote).
<?php
/*
* Plugin Name: Random Quotes
*/
function random_quote($atts) {
extract( shortcode_atts( array(
'path' => plugin_dir_path(__FILE__).'quotes.txt',// default, if not set
'label_new' => 'New Quote',
'words' => 'no' // yes or no
), $atts ) );
$temp = $attr['words']; // no
...
}
add_shortcode('randomquotes','random_quote');
function new_quote(){
global $temp; // NULL
/*
global $attr;
$temp = $attr['words']; // again NULL
*/
...
if($temp == "no") {
...
}
}
...
?>
What am I doing wrong? Maybe just can not get the value of this variable?
It looks like you need to declare global $temp within your random_quote() function. Right now, random_quote() is using a local version of $temp, which is lost when the function is completed.
EDIT: Here's an example snippet
<?php
function test() {
global $temp;
$temp = 'no';
}
function my_test() {
global $temp;
var_dump($temp);
}
test();
my_test();
?>

How to access a member variable of different function in a codeigniter controller

//first function
function insertdigit(){
$userdigit=5;
$flag = $this->usermodel->userdigitmodel($userdigit);
$value = array(
'result' => $flag
);
echo json_encode($value);
if ($flag == true) {
return $userdigit;
} else {
}
}
//second function
function usedigit(){
$data['userdigit']=$this->insertdigit();
}
but i get {"result":true} goes back to the function? how to access a member variable in a different member function
Try to remove echo json_encode($value); in your code.
If you need to access a parameter in several functions on your controller, you have to create it outside your function so it will be available for all your controller functions.
So, in your case it should be something like this:
class Test extends Controller
{
private $userdigit; //here you can set a default value if necessary: private $userdigit = 5
function insertdigit(){
$this->userdigit=5;
$flag = $this->usermodel->userdigitmodel($this->userdigit);
$value = array(
'result' => $flag
);
echo json_encode($value);
if ($flag == true) {
return $this->userdigit;
} else {
}
}
//second function
function usedigit(){
$data['userdigit']=$this->userdigit;
}
}
This way your userdigit variable is available for all your functions. With $this you are telling PHP that you are trying to access something inside the class.
This link contain more and useful information: http://www.php.net/manual/en/language.oop5.properties.php
Is that what you really need?
A possible solution:
function insertdigit()
{
$userDigit = 5;
$flag = $this->usermodel->userdigitmodel($userDigit);
$value = array
(
'result' => $flag
);
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')
{
echo json_encode($value);
}
if ($flag == true)
{
return $userdigit;
}
else
{
}
}
//second function
function usedigit()
{
$data['userdigit'] = $this->insertdigit();
}
The above code, in insertdigit detects if there is an Ajax request and if so, it will echo out the json_encoded data. If you call it in an normal request, i.e. via usedigit it won't echo the json_encoded data (unless you are calling usedigit via an Ajax request).
Your question doesn't really explain what you are doing, so it's hard to explain a better solution, however, if you are trying to access a "variable" in more than one place, you should really separate your code so you have a single entry point for that variable.
Is your variable dynamic, or is it static?

PHP Make a simple if-isset-empty function

I'm coding a worksheet app for a printer company.
I'm getting flood of forms.
For every single input field I have to check if the $_POST variables are set, and if, so echo back the value. (In case of some error, for example after a validation error, the user shouldn't retype the whole form)
Sample code:
if(isset($_POST['time'])&&!empty($_POST['time'])){echo $_POST['time'];}
I had to implement this about a hundred times.
So I tried to figure out some kind of function to make this simple and readable.
Something like this:
function if_post_echo($key, $default = "") {
if(isset($_POST[$key])&&!empty($_POST[$key])){
echo $_POST[$key];
}else{
echo $default;
}
}
But this wont work.
I have tried to pass in the $_POST for the $key variable like this:
if_post_echo($_POST['time'])
function if_request_echo($key, $default = "") {
if(isset($key)&&!empty($key)){
echo $key;
}else{
echo $default;
}
}
And I also tried this:
function if_request_echo($key, $default = null) {
return isset($_REQUEST[$key])&&!empty($_REQUEST[$key]) ? $_REQUEST[$key] : $default;
}
Without any reasonable outcome.
The question:
How can I forge a function that looks for the necessary $_POST variable and returns it or if its unset then returns an empty string.
And is there a way to do this for $_GET and $_REQUEST, too? (Or simply duplicate?)
Your PHP testing function:
<?php
function test_req($key, $default = '') {
if(isset($_REQUEST[$key]) and
!empty($_REQUEST[$key])) {
return $_REQUEST[$key];
} else {
return $default;
}
}
?>
Then in your form HTML:
<input name="my_field" value="<?php echo htmlentities(test_req('my_field')); ?>" />
$_REQUEST (linked) is a PHP super global that contains both POST ($_POST) and GET ($_GET) request parameters.
If you only want to capture POST request parameters then it would be:
<?php
function test_req($key, $default = '') {
if(isset($_POST[$key]) and
!empty($_POST[$key])) {
return $_POST[$key];
} else {
return $default;
}
}
?>
For example.
If you have a large amount of fields, I would propose that you also use an array of defaults:
$defaults = array(
"time" => "default",
"name" => "enter name here",
"text..." => "...",
);
$fields = array_filter($_POST) + $defaults;
$fields will then contain a list of form values with either the POST data or a preset default. No isset, see?
array_filter man page particularly: If no callback is supplied, all entries of input equal to FALSE will be removed. Goes some way to explaining the working behind this solution.
This should work:
function if_post_echo($key, $default = ''){
if(isset($_POST[$key]) AND !empty($_POST[$key]){
echo $_POST[$key];
}
echo $default;
}
If you're having problems I recommend that you try var_dump($_POST) or print_r($_POST) to see if everything has been properly posted.
Just to note, this is redundant:
isset($_POST[$key]) && !empty($_POST[$key])
An unset variable is going to always be "empty", so isset() is implied in your empty() call.
For your logic you can achieve the same result with just:
!empty($_POST[$key])
Your first function works perfectly to me.
Why do you think it doesn't work?
However, a better variant would be
function _post($key, $default = "") {
if(isset($_POST[$key])){
return $_POST[$key];
}else{
return $default;
}
}
To use it :
echo $_post($key); // You could define the message as a second parameter.
function requireArray( $array, $required ) {
foreach( $required as $k=>$v ) {
if ( !isset($array[$k]) || empty($array[$k]) )
return false;
}
return true;
}
#call like this:
requireArray($_POST, array('time', 'username', 'foo'));
If you want to know specifically:
function missingFrom( $array, $required ) {
$r = array();
foreach( $required as $k ) {
if ( !isset($array[$k]) || empty($array[$k]) )
$r[] = $k;
}
return $r;
}
Called like previous function.
Your method seems to work fine here:
function if_post_echo($key, $default = "") {
if(isset($_POST[$key])&&!empty($_POST[$key])){
echo $_POST[$key];
}else{
echo $default;
}
}
I made a simple input with the name test and the form method is POST and using echo if_post_echo('test');.
It posted on the page what was in the text box.
This feature is being added in PHP 7 as the "Null Coalesce Operator" using two question marks:
echo ($_GET['message'] ?? 'default-if-not-set');
https://wiki.php.net/rfc/isset_ternary

Categories