&引用;“中断”;使用PHP的一组带有H2的列表项

&引用;“中断”;使用PHP的一组带有H2的列表项,php,html,css,wordpress,while-loop,Php,Html,Css,Wordpress,While Loop,我正在使用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

我正在使用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; ?>


跟踪
$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;
?>


如果您使用诸如“getId()”之类的函数名而不是“the_ID()”^Hey Dirk,那么代码的可读性将得到很大提高。对不起,我很快会联系WordPress的,关于这件事-那些流氓!!;-)这真的是Wordpress的风格吗?哎哟请原谅我的评论!你说得对。我想得越多,就越倾向于在
li
中放置
h2
,并在
li
中实际执行while循环。或者更适合使用多个列表?然后,您的
标题将简单地为每个列表添加前缀。您好,w3d,很遗憾,这种复杂的AJAX工作方式我认为它不适合这种情况。如果我只是在该类别的第一个
li
之前添加
h2
,会不会太顽皮(非语义)?我不会说;-)我尝试了您上面发布的解决方案,但不确定如何添加正确的
h2
。有什么想法吗?好的,设法正确显示:-)-现在唯一的小问题是当我开始点击AJAX链接时H2消失了。该调查了,看来你已经解决了。要回答您先前的问题。。。如果将
h2
直接放在
li
之前,则会使HTML无效。如果HTML无效,则其行为未定义,可能会在某些浏览器中中断。我还更新了代码以包含示例输出。