提问者:小点点

我如何包装每个3职位在一个div与类别名称包括?


我使用WordPress,我想包装每3个职位在一个div。这应该很容易,但是为了让事情变得更复杂,我还想列出这些div中的类别名称。

我的代码:

<?php
$i = 1;
$taxonomy = 'category';
$param_type = 'category__in';
$term_args=array(
  'orderby' => 'name',
  'order' => 'DESC',
  'child_of'      => 4
 );
$terms = get_terms($taxonomy,$term_args);
echo '<div>';
if ($terms) {
  foreach( $terms as $term ) {
    $args=array(
      "$param_type" => array($term->term_id),
      'post_type' => 'post',
      'post_status' => 'publish',
      'posts_per_page' => -1,
      'caller_get_posts'=> 1
      );
    $my_query = null;
    $my_query = new WP_Query($args);
    if( $my_query->have_posts() ) {
      echo '<h1>' . $term->name . '</h1>' ;
      while ($my_query->have_posts()) : $my_query->the_post();
       if($i % 3 == 0) {echo '</div><div>';} ?>
      <a>"> <?php the_post_thumbnail(); ?> </a>
       <?php
   $i++;
      endwhile;
    }
  }
}
echo '</div>';
wp_reset_query();
?>

我的预期结果是:

<div>
<h1>Category01</h1>
<a><img /></a>
<a><img /></a>
</div>

<div>
<a><img /></a>
<a><img /></a>
<h1>Category02</h1>
</div>

<div>
<a><img /></a>
<a><img /></a>
<a><img /></a>
</div> // etc.

我的问题是,如果我关闭Foreach循环中的div,它只在3后关闭


共1个答案

匿名用户

好的,这是一个工作代码:

<?php
$taxonomy = 'category';
$param_type = 'category__in';
$term_args=array(
  'orderby' => 'name',
  'order' => 'DESC',
  'child_of'      => 4,
 );
$terms = get_terms($taxonomy,$term_args);
if ($terms) {
  $i = 0;
  echo "<div>\n";
  foreach( $terms as $term ) {
    $args=array(
      "$param_type" => array($term->term_id),
      'post_type' => 'post',
      'post_status' => 'publish',
      'posts_per_page' => -1,
      'caller_get_posts'=> 1
      );
    $my_query = null;
    $my_query = new WP_Query($args);
    if( $my_query->have_posts() ) {
       $h1 = '<h1>' . $term->name . '</h1>' ;
      while ($my_query->have_posts()) : $my_query->the_post();
         if ($h1) {
            if (++$i % 3 == 1 && $i > 1) {
               echo "</div><div>\n";
            }
            echo $h1;
            $h1 = '';
         }
         if(++$i % 3 == 1) {echo "</div><div>\n";} ?>
         <a href="<?php the_permalink(); ?>"> <?php the_post_thumbnail(); ?> </a>
      <?php
      endwhile;
     }
  }
  echo "</div>\n";
}
wp_reset_query();
?>