WordPress 从帖子中获取第一张图片
试图从帖子中获取第一张图片,但我的 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; ?>
不知道出了什么问题,因为我使用类似的代码来获取所有图像附件,而不仅仅是一个,而且效果很好。
Trying to get the first image from a post, but my php code doesn't return anything, any help?
<?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; ?>
Not sure what's going wrong as I'm using a similar code to get all of the image attachments and not just one, and that works fine.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

发布评论
评论(2)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
get_children()
仅返回已直接上传到该帖子的图像。如果图像已附加到给定帖子,它将不会被视为其子图像,因此不会由上述函数返回。检查帖子子项的一个简单方法是登录仪表板并转到帖子、编辑帖子。单击编辑器上方的
添加媒体
按钮,然后从唯一的下拉框中选择上传到此帖子
。如果为空,则无论帖子内容如何,get_children都不会返回任何图像。get_children()
only returns images that have been uploaded directly to that post. If an image has been attached to a given post it will not be considered one it's children and thus wont be returned by the afore mentioned function.An easy way to check a post's children is login to the dashboard and go to posts, edit post. Click the
Add Media
button above the editor and from the only drop down box selectUploaded to this post
. If this is empty then get_children will not return any images regardless of the post's content.