I search a lot, but I don´t finde the right solution.
I have a custome field, called "My-Name". This custome field can be added at a post (more then once) or not.
$my_name = get_post_custom_values( 'My-Name' );
foreach ( $my_name as $my_name )
echo $my_name;
My problem - if this key is not available at a post, I get an Error (Warning: Invalid argument supplied for foreach()).
I dont want this Error-Message, I want an "else = html text" if the key isn´t available at this post. I try some if / else, but my php skills are too low for a sucess. Can someone help me?
UPDATE:
I have modify the script from dingo_d and now it works - thx!
$my_name = get_post_custom_values( 'My-Name' );
if(is_array($my_name) && !empty($my_name)){
foreach($my_name as $my_name){
echo $my_name . "
";
}
} else{
echo 'My text';
}
$my_name = get_post_custom_values( 'My-Name' );
if(isset($my_name))
{
foreach ( $my_name as $my_name ){
echo $my_name;
}
}else{
echo "html goes here";
}
Depending on what get_post_custom_values() will return on a missing POST param, just check for the parameter being set or empty:
if (isset($my_name))
{
foreach(...) ...
}
vs.
if (!empty($my_name))
{
foreach(...) ...
}
By the way: An if-else-construct is not a loop ;-)
Always check if your variable is filled with something before entering the foreach loop. That also depends on the type of return you expect as well. I'd do something like:
if(is_array($my_name) && !empty($my_name)){
foreach($my_name as $value){
echo $value;
}
} else{
echo 'My text';
}
This is because your $my_name
variable should return an array. Should your return value be string you'd check if it's set and if it's not an empty string with
if(isset($my_variable) && $my_variable != ''){...}