使用 PHP 使用 H2 “分解”一组列表项


"Break" a set of list items with an H2 using PHP

我正在使用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在这里可能更合适。