我正在使用WordPress,我想在div中包含每个3个帖子。它应该很容易,但为了使事情变得更复杂,我还想在这些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个<h1>
标记后关闭,但如果我在while循环中关闭它们,它会在3个图像后关闭,但是{{ 1}}标签不计入3个元素。有帮助吗?我现在,可以用JavaScript解决它,但我宁愿让它在服务器上运行
答案 0 :(得分:0)
好的,这是一个有效的代码:
<?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();
?>