PHP wordpress函数在函数文件中不执行

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){

            $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

dql1978dql1978 那更有效率的感谢,但是有什么想法可以解决这个问题
接近 7 年之前 回复
duanji4449 我唯一能想到的(但不太可能)是get_posts函数不是全局的。尝试将函数顶部的$return设置为false,以便您可以查看它是否甚至尝试设置它...
接近 7 年之前 回复
doupingpeng7567 你的foreach循环只返回最后的特色图像,因为你在那里做了一个直的=赋值。你说只想要一个,所以这在技术上是正确的。但是如果你最终将大量图像附加到帖子上,那么你将浪费很多周期来构建/丢弃字符串。考虑使用end()简单地跳转到数组的末尾,使用current()来获取该特定元素。
接近 7 年之前 回复


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:

dongzhong8691 谢谢,但仍然没有为某些帖子返回数组,没有解释原因。
接近 7 年之前 回复

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;
Csdn user default icon