PHP wordpress函数在函数文件中时未执行


PHP wordpress function not executing when in functions file

下面的函数会查找Wordpress特色图像,如果帖子没有,它会搜索帖子的第一个附件图像,并使用它。

当在页面上使用PHP时,它可以完美地执行,但是当我试图将它用作可以调用的函数时,ELSE部分中的第二部分在某些帖子中不起作用。

我用SQL查询检查过它,没有理由认为它不起作用。

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;
}

调用页面如下:

echo title_image('full',get_the_ID(),'featuredimg');

为什么这在放置在页面上时有效,而在作为函数

调用时无效

get_posts参数中,设置post状态和mime类型:

'post_status' => 'inherit',
'post_mime_type' => 'image'

此外,您不应该使用guid,使用wp_get_attachment_image_src():获取附件src

foreach( $imgs as $img ){
    $thumb = wp_get_attachment_image_src( $img->ID, $size, false );
    $return = '<img src="' . $thumb[0] . '" class="' . $class . '" />';
}

我建议使用get_children来检索附件,而不是get_posts:

http://codex.wordpress.org/Function_Reference/get_children#Show_the_first_image_associated_with_the_post

仍然没有解释原因,但问题出在has_post_thumbnail()函数上。

对于一些帖子来说,这是真的,原因我无法解释,因为它们没有特色图片。

代码被修改以绕过这一点:

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;
}