我需要在 wordpress 中获取帖子的第一张图片。 我有各种职位。所以对于新帖子,我可以设置特色图片。但是有成千上万的旧帖子。我需要从这些帖子中提取第一张图片,以便我可以使用它们来显示。
我使用了 http://css-tricks.com/snippets/wordpress/get-the-first-image-from-a-post/ 中的代码而且我认为它不适合我。
global $post;
$args = array( 'posts_per_page' => 10, 'category' => 6 );
$myposts = get_posts( $args );
foreach( $myposts as $post ) : setup_postdata($post);
......
.....
endforeach;
我需要以缩略图的形式显示每个帖子中的图像,比如在画廊中。我搜索了很多但无法弄清楚如何。
最佳答案
将其放入您的 functions.php
function getTheFirstImage() {
$files = get_children('post_parent='.get_the_ID().'&post_type=attachment&post_mime_type=image');
if($files) :
$keys = array_reverse(array_keys($files));
$j=0; $num = $keys[$j];
$image=wp_get_attachment_image($num, 'large', false);
$imagepieces = explode('"', $image);
$imagepath = $imagepieces[1];
$thumb=wp_get_attachment_thumb_url($num);
echo "<img src='$thumb' class='thumbnail' />";
endif;
}
然后在您的模板中使用 getTheFirstImage()
函数来打印图像
$args = array( 'posts_per_page' => 10, 'category' => 6 );
$myposts = get_posts( $args );
foreach( $myposts as $post ) : setup_postdata($post);
getTheFirstImage(); // Will print the image
......
.....
endforeach;
关于php - 从wordpress帖子中获取图片(帖子内容),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17353100/