doter1995 2013-11-25 14:45
浏览 48

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



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

  • 写回答

2条回答 默认 最新

  • drol55885602 2013-11-25 15:01
    关注

    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:

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

    评论

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料