【问题标题】:How can I wrap each 3 posts in a div with category names included?如何将每 3 个帖子包装在一个包含类别名称的 div 中?
【发布时间】:2014-07-15 03:55:48
【问题描述】:

我正在使用 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 个 &lt;h1&gt; 标签后关闭,但如果我在 while 循环中关闭它们,它会在 3 张图片后关闭,但 &lt;h1&gt; 标签不计入3个元素。有什么帮助吗?我现在,可以用 JavaScript 解决它,但我更愿意让它在服务器上工作

【问题讨论】:

标签: php html wordpress


【解决方案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();
?>

【讨论】:

    猜你喜欢
    • 2011-12-19
    • 2013-03-03
    • 2017-06-06
    • 2016-11-30
    • 2011-03-22
    • 1970-01-01
    • 2014-01-22
    • 1970-01-01
    相关资源
    最近更新 更多