【问题标题】:Wordpress get first image from a postWordpress 从帖子中获取第一张图片
【发布时间】:2026-02-12 05:40:01
【问题描述】:

试图从帖子中获取第一张图片,但我的 php 代码没有返回任何内容,有什么帮助吗?

<?php while ($browndog_blog->have_posts()) : $browndog_blog->the_post();                    
    $args = array(
    'numberposts' => 1,
    'post_mime_type' => 'image',
   'post_parent' => $post->ID,
    'post_status' => null,
    'post_type' => 'attachment'
    );

    $attachments = get_children( $args );

    //print_r($attachments);

    if ($attachments) {
        foreach($attachments as $attachment) {
            $image_attributes = wp_get_attachment_image_src( $attachment->ID, 'thumbnail' )  ? wp_get_attachment_image_src( $attachment->ID, 'thumbnail' ) : wp_get_attachment_image_src( $attachment->ID, 'full' );

            echo '<a href="'.get_permalink($post->ID).'"><img src="'.wp_get_attachment_thumb_url( $attachment->ID ).'"></a>';
            echo '<p>'.get_the_excerpt($post->ID).'</p>';
            echo '<p><a href="'.get_permalink($post->ID).'">Read More</a></p>';
        }
    }
endwhile; ?>

不知道出了什么问题,因为我正在使用类似的代码来获取所有图像附件,而不仅仅是一个,而且效果很好。

【问题讨论】:

标签: php wordpress loops echo


【解决方案1】:

我想我只是做了和你想做的事情一样的事情......我不会声称自己是一位大师,但这是我为使其工作而做的事情,如果幸运的话,你将能够适应它满足您的需求。

$image_id=get_post_thumbnail_id();
$image_url = wp_get_attachment_image_src($image_id,’large’);
$image_url=$image_url[0];

数组中的第一个图像基本上是缩略图,据我了解,这就是为什么我先获取缩略图 id,然后使用它来检索图像的大版本。

【讨论】:

    【解决方案2】:

    get_children() 仅返回已直接上传到该帖子的图像。如果图像已附加到给定的帖子,则不会将其视为子图像,因此上述函数不会返回。

    检查帖子子项的一种简单方法是登录仪表板并转到帖子,编辑帖子。单击编辑器上方的Add Media 按钮,然后从唯一的下拉框中选择Uploaded to this post。如果这是空的,那么无论帖子的内容如何,​​get_children 都不会返回任何图像。

    【讨论】: