Php 从自定义post类型库附件获取第一个图像
我已经在wordpress主题中创建了自定义的post类型相册。每个帖子都成功地附加了一个图像库。附加到库中所有父帖子的所有图像都将使用以下方式显示在前端:Php 从自定义post类型库附件获取第一个图像,php,wordpress,custom-post-type,image-gallery,Php,Wordpress,Custom Post Type,Image Gallery,我已经在wordpress主题中创建了自定义的post类型相册。每个帖子都成功地附加了一个图像库。附加到库中所有父帖子的所有图像都将使用以下方式显示在前端: <ul id="gallery"> <?php $post_type = 'albums'; $args= array( 'post_type' => 'attachment', 'post_status' => 'inherit', 'post_mime_type' =&
<ul id="gallery">
<?php
$post_type = 'albums';
$args= array(
'post_type' => 'attachment',
'post_status' => 'inherit',
'post_mime_type' => 'image',
'fields' => 'id=>parent',
'order' => 'DESC',
'posts_per_page' => -1
);
// get all image parent post ids
$image_parents = get_posts( $args );
if ( $image_parents ) {
$parent_posts = get_posts( 'fields=ids&post_type=' . $post_type ); // query
if ( $parent_posts ) {
// getting all parent posts by post type that have images
$parent_posts_with_images = $parent_posts;
if ( $parent_posts_with_images ) {
// loop through all post type posts that have images
foreach ( $parent_posts_with_images as $post_id ) {
$args = array(
'post_parent' => $post_id,
'post_status' => 'inherit' ,
'post_type' => 'attachment',
'post_mime_type' => 'image',
'orderby' => 'rand',
'posts_per_page' => -1
);
$images = get_children( $args );
if ( $images ) {
foreach ( (array) $images as $image )
{ ?>
<li class="gallery-item">
<div class="gallery-image">
<?php
$img_url = wp_get_attachment_url( $image->ID );
$image = $img_url;
echo '<a href="'.$img_url.'" class="album-img" id="" title="'.$post_title.'" >
<img src="'.$image.'" alt=""/></a>';
?>
</div>
</li>
<?php }
}
}
}
}
}
?>
</ul>
通过这种方式,我获得了所有50张图片,例如5张帖子,10张图片附在前端的每个图库上。现在,我不想在显示页面上获取所有图库图像,我只希望每个图库中的第一个图像连接到自定义帖子类型的父帖子。并希望在单击第一个图像后使用第一个图像初始化我的灯箱/颜色框或任何其他滑块。请帮助我修改代码
如果我已经创建了5个自定义帖子类型的帖子,如汽车、自行车、自然、时尚、徽标,并将各自的图像库附加到这些帖子上。那么我首先只想显示汽车、自行车、自然、时尚和徽标的第一个图像 如果您限制返回的图像数量,这不是很有帮助吗每页帖子“=>-1$images=get_children$args;如果$images{`=>“每页帖子”=>1是的!使用“按菜单顺序”和“每页帖子”=>1只显示图库的第一个图像。但我的问题是,我可以使用一组相应的图像初始化任何滑块或灯箱图库视图。我不想限制图库显示的图像,只想首先显示第一个图像并隐藏其他图像图像,与大多数图像滑块通常所做的相同。我必须说我不太明白您想要什么。但是在设置$images数组后,您可以使用:$images[0]->ID获取第一个图像的ID。哦,post的ID是键。因此使用以下命令:$firstimage=reset$images;->返回数组的第一个值。echo$firstimage->ID;->post对象的ID
ul#gallery{width:100%;height:100%;position:relative;background:white}
ul#gallery li.gallery-item{width:20%; height:200px;overflow;hidden;}
li.gallery-item .gallery-image{ width:100%;height:100%;}
li.gallery-item .gallery-image img { width:100%;height:100%;display:block}