I’m getting a weird error in my WordPress site. It’s something about an illegal string offset. Here’s what it says:
Warning: Illegal string offset 'alt' in custom_functions.php
Warning: Illegal string offset 'title' in custom_functions.php
This is happening in my theme’s custom functions file. I think it’s related to how the theme handles featured images. Here’s a bit of the code that might be causing it:
function get_featured_image($post_id, $size = 'thumbnail') {
if (has_post_thumbnail($post_id)) {
$image_data = array();
$image_data['url'] = get_the_post_thumbnail_url($post_id, $size);
$image_data['alt'] = get_post_meta(get_post_thumbnail_id($post_id), '_wp_attachment_image_alt', true);
$image_data['title'] = get_the_title(get_post_thumbnail_id($post_id));
return $image_data;
}
return false;
}
I’m not super techy so I’m not sure what’s wrong. Can someone help me figure out how to fix this? Thanks!
I’ve encountered similar issues with string offset warnings in WordPress themes before. From what I can see in your code, the problem likely occurs when a post doesn’t have a featured image set.
The function returns false if there’s no thumbnail, but the code that calls this function might not be checking for that false return value. As a result, it’s trying to access ‘alt’ and ‘title’ keys on a non-array value.
To fix this, you could modify the function to always return an array, even when there’s no featured image. Something like this:
function get_featured_image($post_id, $size = 'thumbnail') {
$image_data = array('url' => '', 'alt' => '', 'title' => '');
if (has_post_thumbnail($post_id)) {
$image_data['url'] = get_the_post_thumbnail_url($post_id, $size);
$image_data['alt'] = get_post_meta(get_post_thumbnail_id($post_id), '_wp_attachment_image_alt', true);
$image_data['title'] = get_the_title(get_post_thumbnail_id($post_id));
}
return $image_data;
}
This should resolve the warnings you’re seeing. Remember to back up your files before making any changes, just in case.
hey charlottew, those errors suck! i had similar probs before. try checking if the image exists before accessing its properties. like this:
if (is_array($image_data) && isset($image_data['alt'])) {
// use $image_data['alt']
}
this should stop the warnings. good luck!