我正在使用 WordPress 生成帖子列表。
输出的 HTML 看起来像这样:
<ul>
<!-- HERE -->
<li id="post-258" class="grid_6 convenience-stores" data-id="post-258">
<h1><a href="/?p=258">Local Store #2</a></h1>
</li>
<li id="post-109" class="grid_6 convenience-stores" data-id="post-109">
<h1><a href="/?p=109">Local Store #1</a></h1>
</li>
<!-- HERE -->
<li id="post-107" class="grid_6 where-to-buy" data-id="post-107">
<h1><a href="/?p=107">Supermarket #2</a></h1>
</li>
<li id="post-105" class="grid_6 where-to-buy" data-id="post-105">
<h1><a href="/?p=105">Supermarket #1</a></h1>
</li>
</ul>
我使用以下 PHP 代码来生成它:
<?php
while (have_posts()) : the_post();
$category = get_the_category();
$class = $category[0]->slug;
?>
<li data-id="post-<?php the_ID(); ?>" class="grid_6 <?php echo $class; ?>" id="post-<?php the_ID(); ?>">
<h1><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h1>
<?php the_content(); ?>
<?php if (has_post_thumbnail( $post->ID ) ): ?>
<?php the_post_thumbnail('small');?>
<?php endif; ?>
</li>
<?php endwhile; ?>
您可以看到我有 2 个不同的类别/HTML 类名称“购买地点”和“便利店”。
现在,我想做的是在类别更改时“打破”循环。
因此,在上面的 HTML 中我标记了 <!-- HERE -->
的位置,我希望我可以添加一个 <h2>
元素来表示下一组帖子的标题。
这可能吗?
如果是这样,我该如何实现?
非常感谢您的帮助。
最佳答案
跟踪 $class
的先前值(例如 $prevClass
)并在循环中检查它。大概这些记录已经在 $class
顺序中了?
<?php
$prevClass = null;
while (have_posts()):
the_post();
$category = get_the_category();
$class = $category[0]->slug;
if ($class != $prevClass) {
/* echo appropriate heading / li here */
/* It needs to be contained in an LI here in order to be valid HTML */
echo "<li><h2>$class</h2></li>"; // Change $class to appropriate heading
}
?>
<li data-id="post-<?php the_ID(); ?>" class="grid_6 <?php echo $class; ?>" id="post-<?php the_ID(); ?>">
<h1><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h1>
<?php the_content(); ?>
<?php if (has_post_thumbnail( $post->ID ) ): ?>
<?php the_post_thumbnail('small');?>
<?php endif; ?>
</li>
<?php
$prevClass = $class;
endwhile;
?>
但是请注意,对于您当前的 HTML 标记,在您标记的位置简单地输出 H2
是无效的 - 这些需要位于 li
。或者,关闭并打开 ul
。
拥有多个 H1
也不一定是个好主意,尽管几个 wordpress 主题似乎确实遵循这种结构。如果您使用的是 HTML5 和 article
/section
那么这可能没问题。 H2
在这里可能更合适。
关于php - "Break"使用 PHP 的一组带有 H2 的列表项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11989670/