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
=assignment in there. You say only want one, so this is technically correct. But if you end up having lots of images attached to a post, you'll be wasting a lot of cycles building/throwing away strings. Consider usingend()to simply jump to the end of the array andcurrent()to get that particular element.get_postsfunction is not global. Try setting$returnat the top of your function to something likefalseso that you can see if it is even trying to set it...