I would like just to add conditionally 's' => $search_term to an array if there is a search term.
$args = array(
// if there is a $search_term then insert:
's' => $search_term
);
I know that I can write many arguments and then using an if statement outside the array but that is way is not what am wishing to do.
You need to do it outside the array as if not the key 's' will be declare anyway in the array (with an empty value if there is no a search term.
Try the following where we insert conditionally a new key / value pair in a defined array:
// Initialize (or define) the array variable
$args = array();
// IF + Condition
if( isset($search_term) && ! empty($search_term) ){
// Inserting in $args array a new key / value pair
$args['s'] = $search_term;
}
Or as explained before, with an always defined 's' key as follow:
$args = array(
's' => isset($search_term) && ! empty($search_term) ? $search_term : '';
);
What you propose cannot be accomplished. The PHP array function is used to declare the keys and values. So, when you write:
$args = array(
's' => $search_term
);
It will create the key 's'. You can do the following
$args = array(
's' => isset($search_term) ? $search_term : null
);
and query with isset($args['s']) to do what you describe, but IMO it is bad to rely on that behavior. isset returns false what array values are null.
The best way is as LoicTheAztec recommends, but you have your workaround here.
Related
--Edited--
I've made a admin form which adds some custom functions to my theme. Loading the settings page I first get the current settings from the database. For this I use get_option().
The setting field is called product_settings
To get all values from this setting you can call it with: $option = get_option('product_settings');
The result of this is equivalent to this:
$option = [
'product_01' => [
'style' => [
'color' => [
'primary' => '#ffffff'
]
]
]
];
Now, to get the value of index 'primary' I would call it like this:
From DB:
$optionColorPrimary = get_option('product_settings')['product_01']['style']['color']['primary'];
From array:
$optionColorPrimary = $option['product_01']['style']['color']['primary'];
Now, this work all fine and that. But now comes the tricky part. The index location is passed in a string value like this:
$get_option_srt = 'product_settings[product_01][style][color][primary]';
First part is the db field. And the part after it, separated by square brackets are the nested indexes.
My Question
How do I get to the nested value of this array based on the indexes from the string?
This is my attempt so far:
$get_option_srt = 'product_settings[product_01][style][color][primary]';
// split in two, to separate the field name from the indexes.
$get_option_srt = preg_split('/(\[.*\])/', $get_option_srt, 2, PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY);
// yes, this does not work...
// The part after get_option() is wrong. Here are the nested index locations needed
$option = get_option( $get_option_srt[0] )[ $get_option_srt[1] ];
Any help is welcome.
I would recommend not attempting to get it directly off the get_option() result, but rather get the value, then parse the path.
You can write your own function that accomplishes what you want. Something like so:
NOTE: This has many "Defensive" measures in place, so that if you ask for a path that doesn't exist, or use a malformed path, this will not throw PHP notices / errors:
function get_option_by_path( $path ) {
// get all the "keys" from within the square braces
preg_match_all( '/\[(.+?)\]/', $path, $matches );
// get the initial "key" (eg, 'product_settings')
$key = explode( '[', $path );
// ensure base key is set, in case there were no square braces
$key = ( ! empty( $key[0] ) ) ? $key[0] : $key;
// load the option value from the DB
$option = get_option( $key );
if ( ! $option || ! is_array( $option ) ) {
return FALSE;
}
// if the passed-in path didn't have any square-brace keys, return the option
if ( empty( $matches[1] ) ) {
return $option;
}
// loop over all the keys in the square braces
foreach ( $matches[1] AS $key ) {
// if $option is an array (still), and has the path, set it as the new $option value
if ( is_array( $option ) && array_key_exists( $key, $option ) ) {
$option = $option[ $key ];
} else {
// otherwise, can't parse properly, exit the loop
break;
}
}
// return the final value for the $option value
return $option;
}
Usage:
$get_option_srt = 'product_settings[product_01][style][color][primary]';
$value = get_option_by_path( $get_option_srt );
You could do this:
$value = 'product_settings[product_01][style][color][primary]';
// The below should result in: 'product_settings[product_01[style[color[primary'
$key_string = str_replace(']', '', $value);
//Create an array for all the values, using '[' as the delimiter
$key_array = explode('[', $key_string);
/* Remove first value (the option name), and save the
value (which is 'product_settings' in this case) */
$option_name = array_shift($key_array);
// Get the option value (an array) from the db:
$option_settings = get_option($option_name);
// Set $option_setting to be the entire returned array:
$option_setting = $option_settings;
/*
Iterate through your key array for as many keys as you have,
changing $option_setting to be more refined on each iteration
until you get the value you need:
*/
for ($i = 0; $i < count($key_array); $i++) {
$option_setting = $option_setting[$key_array[$i]];
}
$option setting should now contain the value you need.
I am new to wordpress and trying build shortcode with parameter using shortcode_atts
I have two array element foo
function bartag_func( $atts ) {
$a = shortcode_atts( array(
'name' => 'vaibhav',
'lname' => 'kulkarni',
), $atts );
return $a;
}
add_shortcode( 'bartag', 'bartag_func' );
and i want to use name and lname as parameter from below code
[bartag name="Alex'" lname="joe"]
if nothing is passed then it should print name as vaibhav and lname as kulkarni
am I doing in correct way? it is printing Array not as individual element.
Please let me know how to access each array element as parameter like this [bartag name="Alex'" lname="joe"]
As i am new to wordpress I think I was doing something in wrong way. return $a returning the whole array so instated of returning array I choose return $a['name']." ".$a['lname']; now with this code i can able to see as per my expected output
I am trying to create php array (associative) declaration for non-empty key-value pairs only, which I am getting from $_POST. Any guesses, how to do this ?
$my_array = [
"k1"=>"$val1",
"k2"=>"$val2",
"k3"=>"$val3",
"k4"=>"$val4"
];
But, if $val4 & $val3 are empty / NULL / does'nt exist, then :
$my_array = [
"k1"=>"$val1",
"k2"=>"$val2"
];
Thanks
As others mentioned you can use array filter,
if you dont want values of 0 being treated as empty you can do something like this
$post = array_filter( $_POST, function( $item ){ return strlen( $item ); });
Array filter will treat 0, '', false, null and I think '0' and possibly some others all as empty. You can use a callback, such as my example. When the call back returns false 0 the item is removed when it returns true ( or > 0 ) it is retained. So strlen will return a value equal to the length of the string and any strings of 0 length are then removed.
-note- this should be fine on $_POST because it's generally not going to have any nested arrays, but if there are nested arrays then strlen will obviously not work on an array ( being this $item = array() in the callback ).
$_POST is already an associative array. For example, with a form, the key is the element 'name' and the value is the user's input. Empty inputs will still generate a key/value pair but you can easily filter these with array_filter()
EDIT:
Here is an example implementation:
array_filter($array, function(x) {
if is_null(x) return false;
else return true;
});
You can write a function to check null or empty values like this:
<?php
function transform(&$data) {
foreach(array_keys($data) as $key) {
if( is_null($data[$key])
|| empty($data[$key])
) {
unset($data[$key]);
}
}
}
// usage
$data = [
"example1" => 5,
"example2" => "some text",
"example3" => null,
"example4" => [],
];
transform($data);
print_r($data);
?>
Example output of print_r() :
Array
(
[example1] => 5
[example2] => some text
)
As this function can take unknown numbers of parameters:
function BulkParam(){
return func_get_args();
}
A print_r will print only the values, but how i can retrieve the variable names as well as the array key? For example:
$d1 = "test data";
$d2 = "test data";
$d3 = "test data";
print_r(BulkParam($d1, $d2, $d3));
It will print this:
Array
(
[0] => test data
[1] => test data
[2] => test data
)
But i want to have the variables name as the index name or key name of all arrays. Then the array would look like this:
Array
(
[d1] => test data
[d2] => test data
[d3] => test data
)
I'm sure the PHP elite will have so many problems with this solution but it does work (I'm using PHP 5.6) and honestly I don't care since I've done hacks far worst than this for prototyping in many of my Java projects.
function args_with_keys( array $args, $class = null, $method = null, $includeOptional = false )
{
if ( is_null( $class ) || is_null( $method ) )
{
$trace = debug_backtrace()[1];
$class = $trace['class'];
$method = $trace['function'];
}
$reflection = new \ReflectionMethod( $class, $method );
if ( count( $args ) < $reflection->getNumberOfRequiredParameters() )
throw new \RuntimeException( "Something went wrong! We had less than the required number of parameters." );
foreach ( $reflection->getParameters() as $param )
{
if ( isset( $args[$param->getPosition()] ) )
{
$args[$param->getName()] = $args[$param->getPosition()];
unset( $args[$param->getPosition()] );
}
else if ( $includeOptional && $param->isOptional() )
{
$args[$param->getName()] = $param->getDefaultValue();
}
}
return $args;
}
Using the PHP Reflections API, we get all the method parameters and align them with their numeric indexes. (There might be a better way to do that.)
To use simply type:
print_r( args_with_keys( func_get_args() ) );
I also added the ability to optionally return the method's optional parameters and values. I'm sure this solution is far from perfect, so you're mileage may vary. Do keep in mind that while I did make it so providing the class and method was optional, I do highly suggest that you specify them if you're going anywhere near a production environment. And you should try to avoid using this in anything other than a prototype setup to begin with.
Specify the class and method with:
print_r( args_with_keys( func_get_args(), __CLASS__, __FUNCTION__ ) );
You can not. Variable names are not passed into functions. Variables are placeholders local to a specific algorithm, they are not data and they do not make sense in another scope and are not passed around. Pass an explicitly named associative array if you need key-value pairs:
bulkParam(['d1' => $d1, 'd2' => $d2, ...]);
A shortcut for this is:
bulkParam(compact('d1', 'd2'));
Then use an array:
function bulkParam(array $params) {
foreach ($params as $key => $value) ...
}
As Mark mentions in the comments, sometimes you don't even have variables in the first place:
bulkParam('foo');
bulkParam(foo(bar(baz())));
Now what?
Or eventually you'll want to refactor your code and change variable names:
// old
$d1 = 'd1';
bulkParam($d1);
// new
$userName = 'd1';
bulkParam($userName);
Your application behaviour should not change just because you rename a variable.
I have an array called $array_all;
This array will always have 3 possible values:
1,
1,2,
1,2,3,
I created a string from the array while in a foreach loop and concatenated a comma at the end.
So, now I have a nice string that outputs the exact value the way it should.
1,2,3, I can copy this output from my browser and insert it into my wordpress function and everything displays perfectly.
The problem arises when I insert this string variable in the wordpress function directly, it fails.
Anybody have any ideas?
Code below:
<?php
$faux_array = array();
$faux_array_all;
if($five_loans != ''):
$faux_array[] = "781";
endif;
if($logbook_loans != ''):
$faux_array[] = "797";
endif;
if($easy_money != ''):
$faux_array[] = "803";
endif;
foreach($faux_array as $faux_array_value):
$faux_array_all .= $faux_array_value . ',';
endforeach;
echo $faux_array_all;
$args = array
(
'posts_per_page' => 10,
'post_type' => 'lender',
'order' => 'ASC',
'orderby' => 'date',
'post__in' => array($faux_array_all)
);
?>
Mmh for one, you can avoid the loop with just:
$faux_array_all = implode(',', $faux_array);
which would also solve the trailing comma proble.m.
On the other hand, you pass an array to post__in that only contains one element (the string). I think what you really want is
'post__in' => $faux_array
as $faux_array is already an array with IDs.
Read about Post & Page Parameters, there you can see that you need to pass an array of post IDs to the function, not an array with one string value:
'post__in' => array(5,12,2,14,7) - inclusion, lets you specify the post IDs to retrieve
'post__in' => $faux_array
Try this, and if it doesn't work post the code that you manually make to work please.
Edited. Check it now.
You need to trim off the trailing comma
foreach($faux_array as $faux_array_value):
$faux_array_all .= $faux_array_value . ',';
endforeach;
if (substr($faux_array_all)-1,1) == ",") {
$faux_array_all = substr($faux_array_all,0,-1);
}