The following function looks for the Wordpress featured image and if the post does not have one, it searches for the first attachment image to the post and uses that instead.
It executes perfectly when in PHP on the page, however when I try to use it as a function that can be called the second part inside the ELSE section is not working on some posts.
Ive checked it with an SQL query and there is no reason why it should not work.
function title_image($size,$post_id,$class){
if(has_post_thumbnail($post_id)){
$return = get_the_post_thumbnail($post_id,$size,array('class' => $class));
}
else {
//Section not working on all posts //
$imgs = get_posts(array('post_type' => 'attachment', 'numberposts' => 1, 'post_parent' => $post_id));
foreach($imgs as $img){
$return = '<img src="'.$img->guid.'" class="'.$class.'" />';
}
}
return $return;
}
Called on page like this:
echo title_image('full',get_the_ID(),'featuredimg');
Why does this work when placed on the page but not when called as a function