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
in the get_posts
args, set the post status and the mime type:
'post_status' => 'inherit',
'post_mime_type' => 'image'
Also, you shouldn't use the guid
, get the attachment src with wp_get_attachment_image_src()
:
foreach( $imgs as $img ){
$thumb = wp_get_attachment_image_src( $img->ID, $size, false );
$return = '<img src="' . $thumb[0] . '" class="' . $class . '" />';
}
I'd recommend to use get_children
to retrieve attachments, instead of get_posts
:
Still no explanation why, but the problem is with the has_post_thumbnail() function.
This was returning true for some posts for a reason I cannot explain as they do not have featured images.
The code is modified to get around this:
function title_image($size,$postid,$class){
$return = get_the_post_thumbnail($postid,$size,array('class' => $class));
if(!$return) {
$imgs = get_children(array('post_type' => 'attachment', 'numberposts' => 1, 'post_parent' => $postid));
foreach($imgs as $img){
$return = '<img src="'.$img->guid.'" class="'.$class.'" />';
}
}
return $return;
}