Firstly, it isn’t an error, it’s a warning:
Warning: Invalid argument supplied for foreach()
It’s showing as an error because your PHP is configured that way. Research error logging levels for more details.
As for why it’s happening:
$my_custom_field = $custom_fields['_source_link']; //key name
foreach ( $my_custom_field as $key => $value )
echo $key . " => <a href="" . $value . "">Click Here</a><br />";
What happens if there is no _source_link
meta field? Or if the field contains an empty array? It is the same as this:
$my_custom_field = false
foreach ( $my_custom_field as $key => $value )
echo $key . " => <a href="" . $value . "">Click Here</a><br />";
Which condenses to:
foreach ( false as $key => $value )
echo $key . " => <a href="" . $value . "">Click Here</a><br />";
This makes no sense, and PHP knows this and outputs a warning.
So instead, don’t assume the data is valid, and check beforehand. empty
is a good way to do this. Here is how I would do it:
$my_custom_field = get_post_meta($post_id, '_source_link', true );
if ( !empty( $my_custom_field ) {
foreach ( $my_custom_field as $key => $value ) {
// display the value
}
} else {
// there are no values
}