1

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>

これは可能ですか?

もしそうなら、どうすればこれを達成できますか?

助けてくれて本当にありがとうございます。

4

1 に答える 1

2

$class(eg. )の以前の値を追跡$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の を使用することも必ずしも良い考えではありませんが、いくつかのワードプレス テーマはこの構造に従っているようです。articleHTML5 と/を使用している場合section、これで問題ない可能性があります。H2ここでは s の方が適切かもしれません。

于 2012-08-16T14:52:35.013 に答える