サポート » テーマ » foreach文で記事を数件毎にタグで囲みたい

  • こんにちは。
    現在、条件に該当する投稿記事を一覧表示させたページを作っております。

    <?php
    $chids = get_term_by('slug',$post->post_name,'ch')->term_id;
    $chs = get_term_children($chids,'ch');
    foreach($chs as $chid) :
    ?>
    
    <div class="post">
    
    	<?php $the_query2 = new WP_Query('posts_per_page=1&post_type=movie&ch='.get_term_by('id',$chid,'ch')->slug);
    	if ( $the_query2->have_posts() ) : while ( $the_query2->have_posts() ) : $the_query2->the_post(); ?>
    
    	<img src="sample.jpg" />
    
    	<?php endwhile; endif; wp_reset_postdata(); ?>
    
    	<?php $the_query = new WP_Query('pagename=ondemand/'.get_term_by('id',$chid,'ch')->slug);
    	if ( $the_query->have_posts() ) : while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
    
    	<h1>タイトル</h1>
    	<p>本文</p>
    
    	<?php endwhile; endif; wp_reset_postdata(); ?>
    
    </div>
    
    <?php endforeach; ?>

    現状、上記のコードで該当記事数だけ

    <div class="post">
    	<img src="sample.jpg" />
    	<h1>タイトル</h1>
    	<p>本文</p>
    </div>

    を吐き出させています。

    それを、2記事毎に<div class=”group”>で自動的に囲み

    <div class="group">
    	<div class="post">
    		<img src="sample.jpg" />
    		<h1>タイトル</h1>
    		<p>本文</p>
    	</div>
    	<div class="post">
    		<img src="sample.jpg" />
    		<h1>タイトル</h1>
    		<p>本文</p>
    	</div>
    </div>

    という形にしたいと考えています。

    過去のフォーラム(http://ja.forums.wordpress.org/topic/1101)のような形では上手くいくのですが、「foreach」文内だとどうも上手くいかず完全に煮詰まってしまいました。

    PHP初心者の為、お手柔らかに教えて頂けると有難いです。
    お詳しい方、宜しくお願いいたします。

1件の返信を表示中 - 1 - 1件目 (全1件中)
  • 次のような処理の流れは如何ですか?

    1. foreachを始める前に、記事を数えるカウンターをゼロにする。
    2. foreachに入ったら最初に、カウンターを2で割って余りがゼロかどうか確かめる。
    3. 余りがゼロなら、class=“group”のdivタグを出力。開始側のdivタグだけです。
    4. 1件の記事をclass=“post”のdivタグで囲んで出力。
    5. もう一度カウンターを2で割った余りがゼロかどうか確かめて、余りが1なら、閉じるdivタグを出力。
    6. カウンターを1増やす。
    7. endforeach
    8. カウンターを2で割った余りがゼロかどうか確かめて、余りが1なら、閉じるdivタグを出力。
1件の返信を表示中 - 1 - 1件目 (全1件中)
  • トピック「foreach文で記事を数件毎にタグで囲みたい」には新たに返信することはできません。