我想在循环时实现WordPress post的以下zigzag div结构...
我的div结构如下......
<div class=wrap>
<div class='a'> Post 1 Content </div>
<div class='b'> Post 2 Content </div>
</div>
<div class=wrap>
<div class='b'> Post 3 Content </div>
<div class='a'> Post 4 Content </div>
</div>
<div class=wrap>
<div class='a'> Post 5 Content </div>
<div class='b'> Post 6 Content </div>
</div>
<div class=wrap>
<div class='b'> Post 7 Content </div>
<div class='a'> Post 8 Content </div>
</div>
答案 0 :(得分:0)
你提到的结构很棘手。
这可以通过以下方式实现,并且可以在我的测试站点中按预期工作。
这是我测试的工作代码:
<?php
$args = array(
'post_type' => 'post',
'posts_per_page' => 8,
);
$query = new WP_Query( $args );
if( $query->have_posts() ):
$post_count = 1;
$wrapper_count = 1;
while( $query->have_posts() ): $query->the_post();
if( $post_count % 2 === 0 ):
$wrapper_count++;
if( $wrapper_count % 2 != 0 ){ ?>
<div class='a'> Post <?php echo $post_count; ?> Content </div>
<?php
} else{ ?>
<div class='b'> Post <?php echo $post_count; ?> Content </div>
<?php
} ?>
</div> <!-- .wrapper end -->
<?php
else: ?>
<div class=wrap> <!-- wrapper start -->
<?php
if( $wrapper_count % 2 != 0 ){ ?>
<div class='a'> Post <?php echo $post_count; ?> Content </div>
<?php
} else{ ?>
<div class='b'> Post <?php echo $post_count; ?> Content </div>
<?php
}
endif;
$post_count++;
endwhile;
endif; ?>
我现在已经发布了一个循环查询,以便您可以根据自定义循环修改代码。
如果您仍然发现任何理解上的困难,请提及我。
谢谢
答案 1 :(得分:0)
尝试使用此代码,这可以很容易地在代码中使用以获取所有帖子。
<?php
$i = 0;
$j = 1;
$row1 = 'a';
$row2 = 'b';
$args = array(
'post_type' => 'post',
'post_status' => 'publish'
);
$posts = get_posts( $args );
?>
<div class="posts">
<?php
foreach($posts as $post):
$post_title = $post->post_title;
if($i % 2 == 0){ ?>
<div class = "wrap">
<?php } ?>
<div class="<?php if($j % 2 == 1) { echo $row1; } else {echo $row2;} ?>"><a href="<?php the_permalink(); ?>"><?php echo $post_title; ?></a> </div>
<?php if($i % 2 == 1){ ?></div><?php } ?>
<?php
$j++;
$i++;
endforeach;
wp_reset_postdata(); ?>
</div>
&#13;
答案 2 :(得分:-2)
$classname = 'a';
while(have_posts()):the_post();
?>
<div class=wrap>
<div class=<?php echo $classname;?>> Post Content </div>
<?php if($classname =='a')$classname = 'b';else $classname = 'a';?>
<div class=<?php echo $classname;?>> Post Content </div>
</div>
<?php
endwhile;