我正在尝试使用Cycle2在Wordpress中创建水平和垂直图像的图片组合,其中所有垂直(肖像)图像成对显示。以下代码有效,但它会显示每个图像两次,一次显示为当前,一次显示为下一次。如果以前显示图像,如何跳过图像?谢谢!
$args = array(
'post_type' => 'attachment',
'numberposts' => -1,
'post_parent' => $post->ID,
);
$attachments = get_posts( $args );
$length = count($attachments);
for($i = 0; $i < $length ; ++$i) {
$attachment = current($attachments);
$next_attachment = next($attachments);
$image_attributes = wp_get_attachment_image_src( $attachment->ID, 'large' );
$next_image_attributes = wp_get_attachment_image_src( $next_attachment->ID, 'large' );
$w = $image_attributes[1];
$h = $image_attributes[2];
$nw = $next_image_attributes[1];
$nh = $next_image_attributes[2];
if($h > $w & $nh > $nw) {
echo '<li>';
echo wp_get_attachment_image( $attachment->ID, 'large' );
echo wp_get_attachment_image( $next_attachment->ID, 'large' );
echo '</li>';
}
答案 0 :(得分:1)
最简单的选择是运行常规循环,每隔一次迭代只输出li
个元素:
$args = array(
'post_type' => 'attachment',
'numberposts' => -1,
'post_parent' => $post->ID,
);
$attachments = get_posts( $args );
echo '<li>';
$counter=0;
foreach($attachments as $attachment){
$image_attributes = wp_get_attachment_image_src( $attachment->ID, 'large' );
$w = $image_attributes[1];
$h = $image_attributes[2];
if($h > $w) {
$counter++;
echo wp_get_attachment_image( $attachment->ID, 'portfolio' );
if($counter %2 == 0){
echo '</li><li>';
}
}
}
echo '</li>';
答案 1 :(得分:1)
史蒂夫的逻辑是正确的,但为了让current
和next
起作用,需要使用for
循环。我需要做的只是计算所有肖像实例并仅输出奇数实例。以下作品:
$args = array(
'post_type' => 'attachment',
'numberposts' => -1,
'post_status' => null,
'post_parent' => $post->ID,
'orderby' => menu_order,
'order' => 'ASC'
);
$attachments = get_posts( $args );
$length = count($attachments);
$counter = 0;
for($i = 0; $i < $length ; ++$i) {
$attachment = current($attachments);
$next_attachment = next($attachments);
$image_attributes = wp_get_attachment_image_src( $attachment->ID, 'large' );
$next_image_attributes = wp_get_attachment_image_src( $next_attachment->ID, 'large' );
$w = $image_attributes[1];
$h = $image_attributes[2];
$nw = $next_image_attributes[1];
$nh = $next_image_attributes[2];
if($h > $w) {
$counter++;
if(($nh > $nw) and ($counter % 2 == 1)) {
echo '<li>';
echo wp_get_attachment_image( $attachment->ID, 'large' );
echo wp_get_attachment_image( $next_attachment->ID, 'large' );
echo '</li>';
} elseif(($nh < $nw) and ($counter % 2 == 1)) {
echo '<li>';
echo wp_get_attachment_image( $attachment->ID, 'large' );
echo '</li>';
} elseif((!$next_attachment) and ($counter % 2 == 1)) {
echo '<li>';
echo wp_get_attachment_image( $attachment->ID, 'large' );
echo '</li>';
}
} elseif($h < $w) {
echo '<li>';
echo wp_get_attachment_image( $attachment->ID, 'large' );
echo '</li>';
$counter = 0;
}
}