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 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch