I inherited a Wordpress website built on an older version of php. I'm getting this error on php 7.4
Trying to access array offset on value of type null in functions.php on line 846 - 849
The four lines are part of some custom code the developer created that I don't entirely understand, so I'm not sure how to fix it. Research leads me to believe it's not checking if the array is empty. I've tried to do that but nothing works. Hoping someone can catch the problem.
Line 846 starts at 'Icon1'
and line 849 at 'Icon4'
function add_icons( $post_id ) {
$MyArray_field = get_field( 'custom_icons', $post_id );
$MyArray = array(
'Icon 1' => $MyArray_field['field_name_1'] ? '<span title="Icon 1">1</span>' : '',
'Icon 2' => $MyArray_field['field_name_2'] ? '<span title="Icon 2">2/span>' : '',
'Icon 3' => $MyArray_field['field_name_3'] ? '<span title="Icon 3">3</span>' : '',
'Icon 4' => $MyArray_field['field_name_4'] ? '<span title="Icon 4">4</span>' : '',
);
$MyArray = array_filter( $MyArray );
return implode( ' ', $MyArray );
}
CodePudding user response:
Check for key exist or not using isset()
try this
function add_icons( $post_id ) {
$MyArray_field = get_field( 'custom_icons', $post_id );
$MyArray = array(
'Icon 1' => isset($MyArray_field['field_name_1']) ? '<span title="Icon 1">1</span>' : '',
'Icon 2' => isset($MyArray_field['field_name_2']) ? '<span title="Icon 2">2/span>' : '',
'Icon 3' => isset($MyArray_field['field_name_3']) ? '<span title="Icon 3">3</span>' : '',
'Icon 4' => isset($MyArray_field['field_name_4']) ? '<span title="Icon 4">4</span>' : '',
);
$MyArray = array_filter( $MyArray );
return implode( ' ', $MyArray );
}
CodePudding user response:
After consulting with a few more developers, it was pointed out to me that it was not an error, but a "Notice:" I was getting on that function so I decided to hide it for now. Yes, it's a hack, but I can't afford to hire someone to fix small problems. If I start getting more problems from the php update, I will come up with a better solution.