如何在循环中仅显示<h1>标签?

时间:2015-11-10 14:46:28

标签: php wordpress loops if-statement

有没有办法强制The Loop只显示帖子内容中的<h1>个标签,同时忽略所有其他标签(h2phr ......)?

  <div id="intro">
  <?php
  $hm_intro = new WP_query(array(
  'p' => 375,
  'post_type' => 'any',
  'posts_per_page' => 1
  ));
  if($hm_intro->have_posts()) : while($hm_intro->have_posts()) : $hm_intro->the_post();

  //Here I want display only the <h1></h1> from the_content().

  endwhile;
  wp_reset_postdata();
  endif;
  ?>
  </div>

1 个答案:

答案 0 :(得分:1)

您可以使用domDocument解析帖子内容中的所有H1:

if($hm_intro->have_posts()) : while($hm_intro->have_posts()) : $hm_intro->the_post();

    $dom = new domDocument;
    $dom->loadHTML(get_the_content());

    $headings = $dom->getElementsByTagName('h1');

    foreach ($heading as $h){
        echo '<h1>' . $h->textContent . '</h1>';
    }

endwhile;